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 --- .../ccsdk/features/sdnr/wt/common/HtAssert.java | 47 +-- .../features/sdnr/wt/common/PropertyService.java | 4 +- .../ccsdk/features/sdnr/wt/common/Resources.java | 118 +++--- .../wt/common/configuration/Configuration.java | 2 +- .../ConfigurationFileRepresentation.java | 402 ++++++++++----------- .../exception/ConfigurationException.java | 2 +- .../wt/common/configuration/subtypes/Section.java | 86 ++--- .../configuration/subtypes/SectionValue.java | 59 +-- .../sdnr/wt/common/database/DatabaseClient.java | 51 ++- .../sdnr/wt/common/database/DatabaseConfig.java | 2 +- .../sdnr/wt/common/database/ExtRestClient.java | 31 +- .../sdnr/wt/common/database/HtDatabaseClient.java | 377 +++++++++---------- .../sdnr/wt/common/database/IsEsObject.java | 4 +- .../sdnr/wt/common/database/Portstatus.java | 18 +- .../sdnr/wt/common/database/SearchHit.java | 6 +- .../sdnr/wt/common/database/SearchResult.java | 77 ++-- .../sdnr/wt/common/database/config/HostInfo.java | 155 ++++---- .../sdnr/wt/common/database/data/AliasesEntry.java | 41 ++- .../wt/common/database/data/AliasesEntryList.java | 54 +-- .../sdnr/wt/common/database/data/DbFilter.java | 66 ++-- .../sdnr/wt/common/database/data/EsVersion.java | 199 +++++----- .../sdnr/wt/common/database/data/IndicesEntry.java | 158 ++++---- .../wt/common/database/data/IndicesEntryList.java | 60 +-- .../common/database/queries/BoolQueryBuilder.java | 112 +++--- .../wt/common/database/queries/QueryBuilder.java | 128 +++---- .../wt/common/database/queries/QueryBuilders.java | 70 ++-- .../common/database/queries/RangeQueryBuilder.java | 118 +++--- .../common/database/queries/RegexQueryBuilder.java | 38 +- .../sdnr/wt/common/database/queries/SortOrder.java | 20 +- .../wt/common/database/requests/BaseRequest.java | 145 ++++---- .../database/requests/ClusterHealthRequest.java | 18 +- .../database/requests/ClusterSettingsRequest.java | 41 ++- .../wt/common/database/requests/CountRequest.java | 12 +- .../database/requests/CreateAliasRequest.java | 8 +- .../database/requests/CreateIndexRequest.java | 19 +- .../database/requests/DeleteAliasRequest.java | 8 +- .../database/requests/DeleteByQueryRequest.java | 27 +- .../database/requests/DeleteIndexRequest.java | 8 +- .../wt/common/database/requests/DeleteRequest.java | 35 +- .../common/database/requests/GetIndexRequest.java | 8 +- .../common/database/requests/GetInfoRequest.java | 8 +- .../wt/common/database/requests/GetRequest.java | 8 +- .../wt/common/database/requests/IndexRequest.java | 64 ++-- .../database/requests/ListAliasesRequest.java | 10 +- .../database/requests/ListIndicesRequest.java | 10 +- .../common/database/requests/NodeStatsRequest.java | 10 +- .../database/requests/RefreshIndexRequest.java | 8 +- .../wt/common/database/requests/SearchRequest.java | 16 +- .../database/requests/UpdateByQueryRequest.java | 148 ++++---- .../wt/common/database/requests/UpdateRequest.java | 240 ++++++------ .../database/responses/AcknowledgedResponse.java | 24 +- .../database/responses/AggregationEntries.java | 33 +- .../wt/common/database/responses/BaseResponse.java | 107 +++--- .../database/responses/ClusterHealthResponse.java | 1 + .../responses/ClusterSettingsResponse.java | 2 +- .../database/responses/CreateAliasResponse.java | 6 +- .../database/responses/CreateIndexResponse.java | 6 +- .../database/responses/DeleteAliasResponse.java | 8 +- .../database/responses/DeleteByQueryResponse.java | 32 +- .../database/responses/DeleteIndexResponse.java | 8 +- .../common/database/responses/DeleteResponse.java | 44 ++- .../common/database/responses/GetInfoResponse.java | 63 ++-- .../wt/common/database/responses/GetResponse.java | 46 +-- .../common/database/responses/IndexResponse.java | 51 +-- .../database/responses/ListAliasesResponse.java | 22 +- .../database/responses/ListIndicesResponse.java | 35 +- .../database/responses/NodeStatsResponse.java | 161 +++++---- .../database/responses/RefreshIndexResponse.java | 20 +- .../common/database/responses/SearchResponse.java | 104 +++--- .../database/responses/UpdateByQueryResponse.java | 69 ++-- .../common/database/responses/UpdateResponse.java | 61 ++-- .../features/sdnr/wt/common/file/FileWatchdog.java | 5 +- .../features/sdnr/wt/common/file/PomFile.java | 109 +++--- .../sdnr/wt/common/file/PomPropertiesFile.java | 112 +++--- .../sdnr/wt/common/http/BaseHTTPClient.java | 6 +- .../sdnr/wt/common/http/BaseHTTPResponse.java | 33 +- .../features/sdnr/wt/common/http/BaseServlet.java | 46 +-- .../features/sdnr/wt/common/test/JSONAssert.java | 335 ++++++++--------- .../features/sdnr/wt/common/util/Environment.java | 30 +- .../sdnr/wt/common/util/ResourceFileLoader.java | 8 +- .../features/sdnr/wt/common/util/StackTrace.java | 1 + 81 files changed, 2499 insertions(+), 2445 deletions(-) (limited to 'sdnr/wt/common/src/main/java/org/onap') diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/HtAssert.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/HtAssert.java index 1ece24161..99a0aaa71 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/HtAssert.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/HtAssert.java @@ -22,6 +22,7 @@ package org.onap.ccsdk.features.sdnr.wt.common; import java.util.Arrays; + /** * * @author Michael Dürre @@ -29,28 +30,28 @@ import java.util.Arrays; */ public class HtAssert { - - public static class HtNullable { - } - - public static void nonnull(Object... oList) { - for (Object o : oList) { - if (o == null) { - throw new IllegalArgumentException( - "One of the date parameters in ["+whoCalledMe()+"] is null (" + Arrays.toString(oList) + ")"); - - } - } - - }; - - private static String whoCalledMe() { - StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); - StackTraceElement caller = stackTraceElements[3]; - String classname = caller.getClassName(); - String methodName = caller.getMethodName(); - int lineNumber = caller.getLineNumber(); - return classname + "." + methodName + ":" + lineNumber; - } + + public static class HtNullable { + } + + public static void nonnull(Object... oList) { + for (Object o : oList) { + if (o == null) { + throw new IllegalArgumentException("One of the date parameters in [" + whoCalledMe() + "] is null (" + + Arrays.toString(oList) + ")"); + + } + } + + }; + + private static String whoCalledMe() { + StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace(); + StackTraceElement caller = stackTraceElements[3]; + String classname = caller.getClassName(); + String methodName = caller.getMethodName(); + int lineNumber = caller.getLineNumber(); + return classname + "." + methodName + ":" + lineNumber; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/PropertyService.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/PropertyService.java index 347971ec2..b391505e9 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/PropertyService.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/PropertyService.java @@ -22,6 +22,6 @@ package org.onap.ccsdk.features.sdnr.wt.common; public interface PropertyService { - - public String getProperty(String property); + + public String getProperty(String property); } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/Resources.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/Resources.java index 2aee0f8e6..bbd1859ed 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/Resources.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/Resources.java @@ -35,72 +35,72 @@ import org.slf4j.LoggerFactory; * * @author Michael Dürre * - * class to get access to internal jar resources + * class to get access to internal jar resources */ public class Resources { - // constants - private static final Logger LOG = LoggerFactory.getLogger(Resources.class); - // end of constants + // constants + private static final Logger LOG = LoggerFactory.getLogger(Resources.class); + // end of constants - // static methods - private static URL getFileURL(Class cls, String resFile) { - Bundle b = FrameworkUtil.getBundle(cls); - URL u = null; - LOG.debug("try to get file {}", resFile); - if (b == null) { - LOG.info("Load resource as file: {}", resFile); - u = getUrlForRessource(cls, resFile); - } else { - LOG.info("Load resource from bundle: {}", resFile); - u = b.getEntry(resFile); - } - return u; - } + // static methods + private static URL getFileURL(Class cls, String resFile) { + Bundle b = FrameworkUtil.getBundle(cls); + URL u = null; + LOG.debug("try to get file {}", resFile); + if (b == null) { + LOG.info("Load resource as file: {}", resFile); + u = getUrlForRessource(cls, resFile); + } else { + LOG.info("Load resource from bundle: {}", resFile); + u = b.getEntry(resFile); + } + return u; + } - private static String readFile(final URL u) throws IOException { - return readFile(u.openStream()); - } + private static String readFile(final URL u) throws IOException { + return readFile(u.openStream()); + } - private static String readFile(final InputStream s) throws IOException { - // read file - final String LR = "\n"; - BufferedReader in = new BufferedReader(new InputStreamReader(s)); - StringBuilder sb = new StringBuilder(); - String inputLine; - while ((inputLine = in.readLine()) != null) { - sb.append(inputLine + LR); - } - in.close(); - s.close(); - return sb.toString(); - } + private static String readFile(final InputStream s) throws IOException { + // read file + final String LR = "\n"; + BufferedReader in = new BufferedReader(new InputStreamReader(s)); + StringBuilder sb = new StringBuilder(); + String inputLine; + while ((inputLine = in.readLine()) != null) { + sb.append(inputLine + LR); + } + in.close(); + s.close(); + return sb.toString(); + } - public static String getFileContent(Class cls, String resFile) { - LOG.debug("loading file {} from res", resFile); - URL u = getFileURL(cls, resFile); - String s = null; - if (u == null) { - LOG.warn("cannot find resfile: {}", resFile); - return null; - } - try { - s = readFile(u); - } catch (Exception e) { - LOG.warn("problem reading file: {}", e.getMessage()); - } - return s; + public static String getFileContent(Class cls, String resFile) { + LOG.debug("loading file {} from res", resFile); + URL u = getFileURL(cls, resFile); + String s = null; + if (u == null) { + LOG.warn("cannot find resfile: {}", resFile); + return null; + } + try { + s = readFile(u); + } catch (Exception e) { + LOG.warn("problem reading file: {}", e.getMessage()); + } + return s; - } + } - public static URL getUrlForRessource(Class cls, String fileOrDirectory) { - //ClassLoader loader = Thread.currentThread().getContextClassLoader(); - ClassLoader loader = cls.getClassLoader(); - URL url = loader.getResource(fileOrDirectory); - if (url == null && fileOrDirectory.startsWith("/")) { - url = loader.getResource(fileOrDirectory.substring(1)); - } - return url; - } - // end of static methods + public static URL getUrlForRessource(Class cls, String fileOrDirectory) { + //ClassLoader loader = Thread.currentThread().getContextClassLoader(); + ClassLoader loader = cls.getClassLoader(); + URL url = loader.getResource(fileOrDirectory); + if (url == null && fileOrDirectory.startsWith("/")) { + url = loader.getResource(fileOrDirectory.substring(1)); + } + return url; + } + // end of static methods } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/Configuration.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/Configuration.java index f0c824c26..8187242cd 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/Configuration.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/Configuration.java @@ -26,7 +26,7 @@ package org.onap.ccsdk.features.sdnr.wt.common.configuration; */ public interface Configuration { - String getSectionName(); + String getSectionName(); void defaults(); } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java index 18a69f004..fe43837e2 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/ConfigurationFileRepresentation.java @@ -43,206 +43,206 @@ import org.slf4j.LoggerFactory; */ public class ConfigurationFileRepresentation implements IConfigChangedListener { - // constants - private static final Logger LOG = LoggerFactory.getLogger(ConfigurationFileRepresentation.class); - - private static final long FILE_POLL_INTERVAL_MS = 1000; - private static final String SECTIONNAME_ROOT = ""; - private static final String LR = "\n"; - private static final String EMPTY = ""; - // end of constants - - // variables - /** Related configuration file **/ - private final File mFile; - /** Monitor changes of file **/ - private final ConfigFileObserver fileObserver; - /** List of sections **/ - private final HashMap sections; - // end of variables - - // constructors - public ConfigurationFileRepresentation(File f) { - - this.mFile = f; - this.sections = new HashMap(); - try { - if (!this.mFile.exists()) { - if (!this.mFile.createNewFile()) { - LOG.error("Can not create file {}", f.getAbsolutePath()); - } - } - reLoad(); - - } catch (IOException e) { - LOG.error("Problem loading config file {} : {}", f.getAbsolutePath(), e.getMessage()); - } - this.fileObserver = new ConfigFileObserver(f.getAbsolutePath(), FILE_POLL_INTERVAL_MS); - this.fileObserver.start(); - this.fileObserver.registerConfigChangedListener(this); - } - - public ConfigurationFileRepresentation(String configurationfile) { - this(new File(configurationfile)); - } - // end of constructors - - // getters and setters - public synchronized Optional
getSection(String name) { - return Optional.ofNullable(sections.get(name)); - } - // end of getters and setters - - // private methods - private synchronized void reLoad() { - sections.clear(); - addSection(SECTIONNAME_ROOT); - load(); - } - - private synchronized void load() { - LOG.debug("loading file {}", getMFileName()); - String curSectionName = SECTIONNAME_ROOT; - Optional
sectionOptional = this.getSection(curSectionName); - Section curSection = sectionOptional.isPresent() ? sectionOptional.get() : this.addSection(curSectionName); - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(this.mFile)); - for (String line; (line = br.readLine()) != null;) { - line = line.trim(); - if (line.isEmpty()) { - continue; - } - if (line.startsWith("[") && line.endsWith("]")) { - curSectionName = line.substring(1, line.length() - 1); - curSection = this.addSection(curSectionName); - } else { - curSection.addLine(line); - } - } - - } catch (Exception e) { - LOG.info("Problem loading configuration file. {} {}", getMFileName(), e); - } finally { - try { - if (br != null) { - br.close(); - } - } catch (IOException e) { - } - } - LOG.debug("finished loading file"); - LOG.debug("start parsing sections"); - for (Section section : this.sections.values()) { - section.parseLines(); - } - LOG.debug("finished parsing " + this.sections.size() + " sections"); - } - - private String getMFileName() { - return mFile.getAbsolutePath(); - } - - // end of private methods - - // public methods - public synchronized Section addSection(String name) { - if (this.sections.containsKey(name)) { - return this.sections.get(name); - } - Section s = new Section(name); - this.sections.put(name, s); - return s; - } - - public synchronized void save() { - LOG.debug("Write configuration to {}", getMFileName()); - try (BufferedWriter bw = new BufferedWriter(new FileWriter(this.mFile, false))) { - for (Section section : this.sections.values()) { - if (section.hasValues()) { - bw.write(String.join(LR, section.toLines()) + LR + LR); - } - } - bw.close(); - } catch (Exception e) { - LOG.warn("problem saving value: " + e.getMessage()); - } - } - - public void registerConfigChangedListener(IConfigChangedListener l) { - this.fileObserver.registerConfigChangedListener(l); - } - - public void unregisterConfigChangedListener(IConfigChangedListener l) { - this.fileObserver.unregisterConfigChangedListener(l); - } - - @Override - public void onConfigChanged() { - LOG.debug("Reload on change {}", getMFileName()); - reLoad(); - } - - @Override - public String toString() { - return "ConfigurationFileRepresentation [mFile=" + mFile + ", sections=" + sections + "]"; - } - - @Override - protected void finalize() throws Throwable { - if (this.fileObserver != null) { - this.fileObserver.interrupt(); - } - super.finalize(); - } - - /* - * Property access set/get - */ - public synchronized void setProperty(String section, String key, Object value) { - Optional
os = this.getSection(section); - if (os.isPresent()) { - os.get().setProperty(key, value == null ? "null" : value.toString()); - save(); - } else { - LOG.info("Unknown configuration section {}", section); - } - } - - public synchronized String getProperty(String section, String propertyKey) { - Optional
os = this.getSection(section); - if (os.isPresent()) { - return os.get().getProperty(propertyKey); - } else { - LOG.debug("Unknown configuration section {}", section); - return EMPTY; - } - } - - public synchronized Optional getPropertyLong(String section, String propertyKey) { - Optional
os = this.getSection(section); - if (os.isPresent()) { - return os.get().getLong(propertyKey); - } else { - LOG.debug("Unknown configuration section {}", section); - return Optional.empty(); - } - } - - public synchronized boolean isPropertyAvailable(String section, String propertyKey) { - Optional
s = this.getSection(section); - return s.isPresent() && s.get().hasKey(propertyKey); - } - - public synchronized void setPropertyIfNotAvailable(String section, String propertyKey, Object propertyValue) { - if (!isPropertyAvailable(section, propertyKey)) { - setProperty(section, propertyKey, propertyValue.toString()); - } - } - - public synchronized boolean getPropertyBoolean(String section, String propertyKey) { - return getProperty(section, propertyKey).equalsIgnoreCase("true"); - } - // end of public methods + // constants + private static final Logger LOG = LoggerFactory.getLogger(ConfigurationFileRepresentation.class); + + private static final long FILE_POLL_INTERVAL_MS = 1000; + private static final String SECTIONNAME_ROOT = ""; + private static final String LR = "\n"; + private static final String EMPTY = ""; + // end of constants + + // variables + /** Related configuration file **/ + private final File mFile; + /** Monitor changes of file **/ + private final ConfigFileObserver fileObserver; + /** List of sections **/ + private final HashMap sections; + // end of variables + + // constructors + public ConfigurationFileRepresentation(File f) { + + this.mFile = f; + this.sections = new HashMap(); + try { + if (!this.mFile.exists()) { + if (!this.mFile.createNewFile()) { + LOG.error("Can not create file {}", f.getAbsolutePath()); + } + } + reLoad(); + + } catch (IOException e) { + LOG.error("Problem loading config file {} : {}", f.getAbsolutePath(), e.getMessage()); + } + this.fileObserver = new ConfigFileObserver(f.getAbsolutePath(), FILE_POLL_INTERVAL_MS); + this.fileObserver.start(); + this.fileObserver.registerConfigChangedListener(this); + } + + public ConfigurationFileRepresentation(String configurationfile) { + this(new File(configurationfile)); + } + // end of constructors + + // getters and setters + public synchronized Optional
getSection(String name) { + return Optional.ofNullable(sections.get(name)); + } + // end of getters and setters + + // private methods + private synchronized void reLoad() { + sections.clear(); + addSection(SECTIONNAME_ROOT); + load(); + } + + private synchronized void load() { + LOG.debug("loading file {}", getMFileName()); + String curSectionName = SECTIONNAME_ROOT; + Optional
sectionOptional = this.getSection(curSectionName); + Section curSection = sectionOptional.isPresent() ? sectionOptional.get() : this.addSection(curSectionName); + BufferedReader br = null; + try { + br = new BufferedReader(new FileReader(this.mFile)); + for (String line; (line = br.readLine()) != null;) { + line = line.trim(); + if (line.isEmpty()) { + continue; + } + if (line.startsWith("[") && line.endsWith("]")) { + curSectionName = line.substring(1, line.length() - 1); + curSection = this.addSection(curSectionName); + } else { + curSection.addLine(line); + } + } + + } catch (Exception e) { + LOG.info("Problem loading configuration file. {} {}", getMFileName(), e); + } finally { + try { + if (br != null) { + br.close(); + } + } catch (IOException e) { + } + } + LOG.debug("finished loading file"); + LOG.debug("start parsing sections"); + for (Section section : this.sections.values()) { + section.parseLines(); + } + LOG.debug("finished parsing " + this.sections.size() + " sections"); + } + + private String getMFileName() { + return mFile.getAbsolutePath(); + } + + // end of private methods + + // public methods + public synchronized Section addSection(String name) { + if (this.sections.containsKey(name)) { + return this.sections.get(name); + } + Section s = new Section(name); + this.sections.put(name, s); + return s; + } + + public synchronized void save() { + LOG.debug("Write configuration to {}", getMFileName()); + try (BufferedWriter bw = new BufferedWriter(new FileWriter(this.mFile, false))) { + for (Section section : this.sections.values()) { + if (section.hasValues()) { + bw.write(String.join(LR, section.toLines()) + LR + LR); + } + } + bw.close(); + } catch (Exception e) { + LOG.warn("problem saving value: " + e.getMessage()); + } + } + + public void registerConfigChangedListener(IConfigChangedListener l) { + this.fileObserver.registerConfigChangedListener(l); + } + + public void unregisterConfigChangedListener(IConfigChangedListener l) { + this.fileObserver.unregisterConfigChangedListener(l); + } + + @Override + public void onConfigChanged() { + LOG.debug("Reload on change {}", getMFileName()); + reLoad(); + } + + @Override + public String toString() { + return "ConfigurationFileRepresentation [mFile=" + mFile + ", sections=" + sections + "]"; + } + + @Override + protected void finalize() throws Throwable { + if (this.fileObserver != null) { + this.fileObserver.interrupt(); + } + super.finalize(); + } + + /* + * Property access set/get + */ + public synchronized void setProperty(String section, String key, Object value) { + Optional
os = this.getSection(section); + if (os.isPresent()) { + os.get().setProperty(key, value == null ? "null" : value.toString()); + save(); + } else { + LOG.info("Unknown configuration section {}", section); + } + } + + public synchronized String getProperty(String section, String propertyKey) { + Optional
os = this.getSection(section); + if (os.isPresent()) { + return os.get().getProperty(propertyKey); + } else { + LOG.debug("Unknown configuration section {}", section); + return EMPTY; + } + } + + public synchronized Optional getPropertyLong(String section, String propertyKey) { + Optional
os = this.getSection(section); + if (os.isPresent()) { + return os.get().getLong(propertyKey); + } else { + LOG.debug("Unknown configuration section {}", section); + return Optional.empty(); + } + } + + public synchronized boolean isPropertyAvailable(String section, String propertyKey) { + Optional
s = this.getSection(section); + return s.isPresent() && s.get().hasKey(propertyKey); + } + + public synchronized void setPropertyIfNotAvailable(String section, String propertyKey, Object propertyValue) { + if (!isPropertyAvailable(section, propertyKey)) { + setProperty(section, propertyKey, propertyValue.toString()); + } + } + + public synchronized boolean getPropertyBoolean(String section, String propertyKey) { + return getProperty(section, propertyKey).equalsIgnoreCase("true"); + } + // end of public methods } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/exception/ConfigurationException.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/exception/ConfigurationException.java index cff2368a2..2c036fed1 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/exception/ConfigurationException.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/exception/ConfigurationException.java @@ -28,4 +28,4 @@ public class ConfigurationException extends Exception { public ConfigurationException(String m) { super(m); } -} \ No newline at end of file +} diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java index 39c00da1d..54ebd03ac 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/Section.java @@ -32,26 +32,27 @@ import java.util.regex.Pattern; import org.onap.ccsdk.features.sdnr.wt.common.configuration.exception.ConversionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + /** * * @author Michael Dürre, Herbert Eiselt * - * subset of configuration identified by its name + * subset of configuration identified by its name */ public class Section { - // constants + // constants private static final Logger LOG = LoggerFactory.getLogger(Section.class); private static final String DELIMITER = "="; private static final String COMMENTCHARS[] = {"#", ";"}; // end of constants - + // variables private final String name; private final List rawLines; private final LinkedHashMap values; // end of variables - + // constructors public Section(String name) { LOG.debug("new section created: '{}'", name); @@ -60,7 +61,7 @@ public class Section { this.values = new LinkedHashMap<>(); } //end of constructors - + // getters and setters public String getName() { return name; @@ -77,7 +78,7 @@ public class Section { return false; } // end of private methods - + // public methods public void addLine(String line) { LOG.trace("adding raw line:" + line); @@ -88,38 +89,38 @@ public class Section { return this.getProperty(key, ""); } - public String getProperty(final String key, final String defValue) { - String value=defValue; - LOG.debug("try to get property for {} with def {}",key,defValue); - if (values.containsKey(key)) { - value = values.get(key).getValue(); - } - //try to read env var - if (value != null && value.contains("${")) { - - LOG.debug("try to find env var(s) for {}",value); - final String regex = "(\\$\\{[A-Z0-9_-]+\\})"; - final Pattern pattern = Pattern.compile(regex); - final Matcher matcher = pattern.matcher(value); - String tmp=new String(value); - while(matcher.find() && matcher.groupCount()>0) { - final String mkey = matcher.group(1); - if(mkey!=null) { - try { - LOG.debug("match found for v={} and env key={}",tmp,mkey); - String env=System.getenv(mkey.substring(2,mkey.length()-1)); - tmp = tmp.replace(mkey, env==null?"":env ); - } catch (SecurityException e) { - LOG.warn("unable to read env {}: {}", value, e); - } - } - } - value=tmp; - } - return value; - } - - + public String getProperty(final String key, final String defValue) { + String value = defValue; + LOG.debug("try to get property for {} with def {}", key, defValue); + if (values.containsKey(key)) { + value = values.get(key).getValue(); + } + //try to read env var + if (value != null && value.contains("${")) { + + LOG.debug("try to find env var(s) for {}", value); + final String regex = "(\\$\\{[A-Z0-9_-]+\\})"; + final Pattern pattern = Pattern.compile(regex); + final Matcher matcher = pattern.matcher(value); + String tmp = new String(value); + while (matcher.find() && matcher.groupCount() > 0) { + final String mkey = matcher.group(1); + if (mkey != null) { + try { + LOG.debug("match found for v={} and env key={}", tmp, mkey); + String env = System.getenv(mkey.substring(2, mkey.length() - 1)); + tmp = tmp.replace(mkey, env == null ? "" : env); + } catch (SecurityException e) { + LOG.warn("unable to read env {}: {}", value, e); + } + } + } + value = tmp; + } + return value; + } + + public void setProperty(String key, String value) { boolean isuncommented = this.isCommentLine(key); @@ -129,7 +130,7 @@ public class Section { if (this.values.containsKey(key)) { this.values.get(key).setValue(value).setIsUncommented(isuncommented); } else { - this.values.put(key, new SectionValue(value,isuncommented)); + this.values.put(key, new SectionValue(value, isuncommented)); } } @@ -155,8 +156,7 @@ public class Section { if (hlp.length > 1) { String key = hlp[0]; String value = - line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) - : ""; + line.length() > (key + DELIMITER).length() ? line.substring((key + DELIMITER).length()) : ""; if (this.values.containsKey(key)) { this.values.get(key).setValue(value); } else { @@ -170,7 +170,7 @@ public class Section { } } - + public String[] toLines() { List lines = new ArrayList<>(); @@ -227,7 +227,7 @@ public class Section { return Optional.of(Long.parseLong(v)); } catch (NumberFormatException e) { } - return Optional.empty(); + return Optional.empty(); } public boolean hasValues() { diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/SectionValue.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/SectionValue.java index 3aacf9a40..a4758f1b5 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/SectionValue.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/configuration/subtypes/SectionValue.java @@ -23,6 +23,7 @@ package org.onap.ccsdk.features.sdnr.wt.common.configuration.subtypes; import java.util.ArrayList; import java.util.List; + /** * * @author Michael Dürre, Herbert Eiselt @@ -30,7 +31,7 @@ import java.util.List; */ class SectionValue { - // variables + // variables private String value; private final List comments; private boolean isUncommented; @@ -48,40 +49,40 @@ class SectionValue { } public SectionValue(String value, boolean isUncommented) { - this(value, new ArrayList(), isUncommented); - } + this(value, new ArrayList(), isUncommented); + } // end of constructors - + // getters and setters - public String getValue() { - return value; - } + public String getValue() { + return value; + } - public SectionValue setValue(String value) { - this.value = value; - return this; - } + public SectionValue setValue(String value) { + this.value = value; + return this; + } - public boolean isUncommented() { - return isUncommented; - } + public boolean isUncommented() { + return isUncommented; + } - public SectionValue setIsUncommented(boolean isUncommented) { - this.isUncommented = isUncommented; - return this; - } + public SectionValue setIsUncommented(boolean isUncommented) { + this.isUncommented = isUncommented; + return this; + } - public List getComments() { - return comments; - } - // end of getters and setters - - // public methods - @Override - public String toString() { - return "SectionValue [value=" + value + ", comments=" + comments + ", isUncommented=" + isUncommented + "]"; - } - // end of public methods + public List getComments() { + return comments; + } + // end of getters and setters + + // public methods + @Override + public String toString() { + return "SectionValue [value=" + value + ", comments=" + comments + ", isUncommented=" + isUncommented + "]"; + } + // end of public methods } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java index 542a7cb08..3a9c10514 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseClient.java @@ -36,14 +36,16 @@ public interface DatabaseClient { /** * Read JSON Object from database + * * @param dataTypeName to read * @param esId to provide id to read * @return String with json structure */ - public @Nullable String doReadJsonData(String dataTypeName, @Nonnull IsEsObject esId ); + public @Nullable String doReadJsonData(String dataTypeName, @Nonnull IsEsObject esId); /** * Read JSON Object from database + * * @param dataTypeName to read * @param esId of object to read * @return String with json structure @@ -52,6 +54,7 @@ public interface DatabaseClient { /** * Provide all Objects of the specified dataTypeName. + * * @param dataTypeName to be used * @return SearchResult with list of elements */ @@ -59,11 +62,13 @@ public interface DatabaseClient { /** * Provide all Objects that are covered by query. + * * @param dataTypeName to be used * @param queryBuilder with the query to be used. * @return SearchResult with list of elements */ public @Nonnull SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder); + /** * Write one object into Database * @@ -72,37 +77,41 @@ public interface DatabaseClient { * @param json String in JSON format. * @return esId String of the database object or null in case of write problems. */ - public @Nullable String doWriteJsonString( String dataTypeName, @Nonnull IsEsObject esId, String json); + public @Nullable String doWriteJsonString(String dataTypeName, @Nonnull IsEsObject esId, String json); /** * Write one object into Database + * * @param dataTypeName Name of datatype * @param esId of object to be replaced or null for new entry. * @param json String in JSON format. * @return esId String of the database object or null in case of write problems. */ - public @Nullable String doWriteRaw( String dataTypeName, @Nullable String esId, String json); + public @Nullable String doWriteRaw(String dataTypeName, @Nullable String esId, String json); /** * Write one object into Database + * * @param indexName Name of index * @param dataTypeName Name of datatype * @param esId of object to be replaced or null for new entry. * @param json String in JSON format. * @return esId String of the database object or null in case of write problems. */ - public @Nullable String doWriteRaw(String indexName,String dataTypeName, @Nullable String esId, String json); - + public @Nullable String doWriteRaw(String indexName, String dataTypeName, @Nullable String esId, String json); + /** * Remove Object from database + * * @param dataTypeName of object * @param esId of object to be deleted * @return success */ - public boolean doRemove( String dataTypeName, IsEsObject esId ); + public boolean doRemove(String dataTypeName, IsEsObject esId); /** * Remove Object from database + * * @param dataTypeName of object * @param esId as String of object to be deleted * @return success @@ -111,6 +120,7 @@ public interface DatabaseClient { /** * Verify if index already created + * * @param dataTypeName to be verified. * @return boolean accordingly */ @@ -118,6 +128,7 @@ public interface DatabaseClient { /** * Update one object in Database with id=esId or create if not exists. + * * @param dataTypeName Name of datatype * @param esId of object to be replaced or null for new entry. * @param json String in JSON format. @@ -127,6 +138,7 @@ public interface DatabaseClient { /** * Update one object in Database with id=esId or create if not exists. + * * @param dataTypeName Name of datatype * @param esId to use for DB object * @param json object to write @@ -137,6 +149,7 @@ public interface DatabaseClient { /** * remove items from database by query + * * @param dataTypeName Name of datatype * @param query query to select items to remove * @return count of removed items @@ -145,6 +158,7 @@ public interface DatabaseClient { /** * update object in database + * * @param dataTypeName Name of datatype * @param json dataobject * @param query query to select item to update @@ -156,7 +170,8 @@ public interface DatabaseClient { * * @param dataTypeName Name of datatype * @param queryBuilder query to select items to read - * @param ignoreException flag if serverside exception will be thrown if query is not valid (needed for user entered filters) + * @param ignoreException flag if serverside exception will be thrown if query is not valid (needed for user entered + * filters) * @return results */ SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder, @@ -165,21 +180,23 @@ public interface DatabaseClient { /** * read all data + * * @param dataTypeName Name of datatype - * @param ignoreException flag if serverside exception will be thrown if query is not valid (needed for user entered filters) + * @param ignoreException flag if serverside exception will be thrown if query is not valid (needed for user entered + * filters) * @return results */ SearchResult doReadAllJsonData(String dataTypeName, boolean ignoreException); - /** - * @param alias - * @param dataTypeName - * @param queryBuilder - * @param ignoreException - * @return - */ - SearchResult doReadByQueryJsonData(String alias, String dataTypeName, QueryBuilder queryBuilder, - boolean ignoreException); + /** + * @param alias + * @param dataTypeName + * @param queryBuilder + * @param ignoreException + * @return + */ + SearchResult doReadByQueryJsonData(String alias, String dataTypeName, QueryBuilder queryBuilder, + boolean ignoreException); diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseConfig.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseConfig.java index 969f0e85c..573c427a2 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseConfig.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/DatabaseConfig.java @@ -25,6 +25,6 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo; public interface DatabaseConfig { - HostInfo[] getHosts(); + HostInfo[] getHosts(); } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java index 70b81990e..9d5e9f648 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/ExtRestClient.java @@ -108,17 +108,18 @@ public class ExtRestClient { HttpAsyncClientBuilder httpAsyncClientBuilder = null; try { httpAsyncClientBuilder = httpClientBuilder.setSSLContext(BaseHTTPClient.setupSsl(this.trustAll)); - if(this.trustAll) { - httpAsyncClientBuilder.setSSLHostnameVerifier(new HostnameVerifier() { - - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); + if (this.trustAll) { + httpAsyncClientBuilder.setSSLHostnameVerifier(new HostnameVerifier() { + + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }); } - } catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) { - LOG.warn("unable to init ssl context for db client: {}",e.getMessage()); + } catch (NoSuchAlgorithmException | KeyManagementException | UnrecoverableKeyException + | CertificateException | KeyStoreException | InvalidKeySpecException | IOException e) { + LOG.warn("unable to init ssl context for db client: {}", e.getMessage()); } if (basicAuthPassword == null || basicAuthUsername == null) { return httpAsyncClientBuilder; @@ -187,12 +188,12 @@ public class ExtRestClient { private final RestClient client; protected ExtRestClient(HostInfo[] hosts) { - this(hosts, null, null,false); + this(hosts, null, null, false); } protected ExtRestClient(HostInfo[] hosts, String username, String password, boolean trustAll) { this.client = RestClient.builder(get(hosts)) - .setHttpClientConfigCallback(new BasicAuthHttpClientConfigCallback(username, password,trustAll)) + .setHttpClientConfigCallback(new BasicAuthHttpClientConfigCallback(username, password, trustAll)) .build(); } @@ -215,6 +216,7 @@ public class ExtRestClient { public ClusterSettingsResponse setupClusterSettings(ClusterSettingsRequest request) throws IOException { return new ClusterSettingsResponse(this.client.performRequest(request.getInner())); } + public CreateAliasResponse updateAliases(CreateAliasRequest request) throws IOException { return new CreateAliasResponse(this.client.performRequest(request.getInner())); } @@ -265,6 +267,7 @@ public class ExtRestClient { /** * Search for database entries + * * @param request inputRequest * @param ignoreParseException especially for usercreated filters which may cause ES server response exceptions * @return Response with related entries @@ -357,12 +360,12 @@ public class ExtRestClient { return new ExtRestClient(hosts); } - public static ExtRestClient createInstance(HostInfo[] hosts, String username, String password,boolean trustAll) { + public static ExtRestClient createInstance(HostInfo[] hosts, String username, String password, boolean trustAll) { return new ExtRestClient(hosts, username, password, trustAll); } public static ExtRestClient createInstance(String hostname, int port, Protocol protocol) { - return createInstance(new HostInfo[] { new HostInfo(hostname, port, protocol) }); + return createInstance(new HostInfo[] {new HostInfo(hostname, port, protocol)}); } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java index 9a369ea5b..e8d86a925 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/HtDatabaseClient.java @@ -53,65 +53,70 @@ import org.slf4j.LoggerFactory; /** * @author Herbert, Micha * - * Hint: Elasticsearch index/alias and doctype will be the same value - * server side restricted since ES 5.0 + * Hint: Elasticsearch index/alias and doctype will be the same value server side restricted since ES 5.0 * */ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, AutoCloseable { - private static final boolean REFRESH_AFTER_REWRITE_DEFAULT = true; - private static final boolean TRUSTALL_DEFAULT = false; + private static final boolean REFRESH_AFTER_REWRITE_DEFAULT = true; + private static final boolean TRUSTALL_DEFAULT = false; - private final Logger LOG = LoggerFactory.getLogger(HtDatabaseClient.class); + private final Logger LOG = LoggerFactory.getLogger(HtDatabaseClient.class); + + private boolean doRefreshAfterWrite; - private boolean doRefreshAfterWrite; public HtDatabaseClient(HostInfo[] hosts) { - this(hosts,REFRESH_AFTER_REWRITE_DEFAULT); - } + this(hosts, REFRESH_AFTER_REWRITE_DEFAULT); + } + public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite) { - this(hosts,refreshAfterWrite,null,null,TRUSTALL_DEFAULT); - } - public HtDatabaseClient(HostInfo[] hosts,String username,String password) { - this(hosts,username,password,TRUSTALL_DEFAULT); + this(hosts, refreshAfterWrite, null, null, TRUSTALL_DEFAULT); } - public HtDatabaseClient(HostInfo[] hosts,String username,String password, boolean trustAll) { - this(hosts,REFRESH_AFTER_REWRITE_DEFAULT,username,password,trustAll); - } - public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite,String username,String password, boolean trustAll) { - super(hosts,username,password,trustAll); - this.doRefreshAfterWrite = refreshAfterWrite; - } - + + public HtDatabaseClient(HostInfo[] hosts, String username, String password) { + this(hosts, username, password, TRUSTALL_DEFAULT); + } + + public HtDatabaseClient(HostInfo[] hosts, String username, String password, boolean trustAll) { + this(hosts, REFRESH_AFTER_REWRITE_DEFAULT, username, password, trustAll); + } + + public HtDatabaseClient(HostInfo[] hosts, boolean refreshAfterWrite, String username, String password, + boolean trustAll) { + super(hosts, username, password, trustAll); + this.doRefreshAfterWrite = refreshAfterWrite; + } + /*---------------------------------- * Functions */ - /** - * Close function - */ - @Override - public void close() { - try { - super.close(); - } catch (IOException e) { - LOG.warn("Problem closing db client: {}",e); - } - } + /** + * Close function + */ + @Override + public void close() { + try { + super.close(); + } catch (IOException e) { + LOG.warn("Problem closing db client: {}", e); + } + } @Override public boolean isExistsIndex(String esIndexAlias) { - LOG.debug("Check status of ES index: {}", esIndexAlias); + LOG.debug("Check status of ES index: {}", esIndexAlias); GetIndexRequest request = new GetIndexRequest(esIndexAlias); - boolean indexStatus = false; - try { - indexStatus = this.indicesExists(request); - } catch (IOException e) { - LOG.warn("Problem checking index for {}: {}",esIndexAlias,e); - } + boolean indexStatus = false; + try { + indexStatus = this.indicesExists(request); + } catch (IOException e) { + LOG.warn("Problem checking index for {}: {}", esIndexAlias, e); + } return indexStatus; @@ -124,16 +129,17 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A @Override public @Nullable String doWriteRaw(String dataTypeName, @Nullable String esId, String json) { - return this.doWriteRaw(dataTypeName, dataTypeName, esId, json); + return this.doWriteRaw(dataTypeName, dataTypeName, esId, json); } + @Override - public @Nullable String doWriteRaw(String indexName,String dataTypeName, @Nullable String esId, String json) { - + public @Nullable String doWriteRaw(String indexName, String dataTypeName, @Nullable String esId, String json) { + IndexResponse response = null; - IndexRequest indexRequest = new IndexRequest(indexName,dataTypeName,esId,this.doRefreshAfterWrite); + IndexRequest indexRequest = new IndexRequest(indexName, dataTypeName, esId, this.doRefreshAfterWrite); indexRequest.source(json); try { - response = this.index(indexRequest ); + response = this.index(indexRequest); } catch (IOException e) { LOG.warn("ES Exception {} Json: {}", e.getMessage(), json); } @@ -142,42 +148,43 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A LOG.warn("Response null during write: {} {}", esId, json); return null; } -// if(this.doRefreshAfterWrite) { -// this.doRefresh(dataTypeName); -// } - return response.getId(); + // if(this.doRefreshAfterWrite) { + // this.doRefresh(dataTypeName); + // } + return response.getId(); } private void doRefresh(String dataTypeName) { - try { - RefreshIndexResponse response = this.refreshIndex(new RefreshIndexRequest(dataTypeName)); - if(!response.succeeded()) { - LOG.warn("seems that index {} was not refreshed",dataTypeName); - } - } catch (IOException e) { - LOG.warn("problem with refreshing index: {}",e); - } - - } - @Override + try { + RefreshIndexResponse response = this.refreshIndex(new RefreshIndexRequest(dataTypeName)); + if (!response.succeeded()) { + LOG.warn("seems that index {} was not refreshed", dataTypeName); + } + } catch (IOException e) { + LOG.warn("problem with refreshing index: {}", e); + } + + } + + @Override public boolean doRemove(String dataTypeName, IsEsObject esId) { - return doRemove(dataTypeName, esId.getEsId()); + return doRemove(dataTypeName, esId.getEsId()); } @Override public boolean doRemove(String dataTypeName, String esId) { - DeleteRequest deleteRequest = new DeleteRequest(dataTypeName,dataTypeName,esId,this.doRefreshAfterWrite); - DeleteResponse response = null; - try { - response = this.delete(deleteRequest); - } catch (IOException e) { - LOG.warn("Problem deleting from db: {}",e.getMessage()); - } -// if(this.doRefreshAfterWrite) { -// this.doRefresh(dataTypeName); -// } - return response!=null?response.isDeleted():false; + DeleteRequest deleteRequest = new DeleteRequest(dataTypeName, dataTypeName, esId, this.doRefreshAfterWrite); + DeleteResponse response = null; + try { + response = this.delete(deleteRequest); + } catch (IOException e) { + LOG.warn("Problem deleting from db: {}", e.getMessage()); + } + // if(this.doRefreshAfterWrite) { + // this.doRefresh(dataTypeName); + // } + return response != null ? response.isDeleted() : false; } @Override @@ -193,118 +200,126 @@ public class HtDatabaseClient extends ExtRestClient implements DatabaseClient, A @Override public @Nullable String doReadJsonData(String dataTypeName, @Nonnull String esId) { - LOG.debug("NetworkIndex read: {}", dataTypeName); - GetRequest getRequest = new GetRequest(dataTypeName,dataTypeName,esId); - GetResponse response = null; - try { - response = this.get(getRequest); - } catch (IOException e) { - LOG.warn("problem reading data {} with id {}: {}",dataTypeName,esId,e); - } - return response!=null && response.isExists() ? response.getSourceAsBytesRef() : null; + LOG.debug("NetworkIndex read: {}", dataTypeName); + GetRequest getRequest = new GetRequest(dataTypeName, dataTypeName, esId); + GetResponse response = null; + try { + response = this.get(getRequest); + } catch (IOException e) { + LOG.warn("problem reading data {} with id {}: {}", dataTypeName, esId, e); + } + return response != null && response.isExists() ? response.getSourceAsBytesRef() : null; + } + + @Override + public @Nonnull SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder) { + + return this.doReadByQueryJsonData(dataTypeName, queryBuilder, false); } - @Override - public @Nonnull SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder) { - - return this.doReadByQueryJsonData(dataTypeName, queryBuilder, false); - } - @Override - public @Nonnull SearchResult doReadByQueryJsonData( String dataTypeName,QueryBuilder queryBuilder, boolean ignoreException) { - return this.doReadByQueryJsonData(dataTypeName, dataTypeName,queryBuilder,ignoreException); - } - @Override - public @Nonnull SearchResult doReadByQueryJsonData(String alias, String dataTypeName,QueryBuilder queryBuilder, boolean ignoreException) { - - long total = 0; - LOG.debug("NetworkIndex query and read: {}", dataTypeName); - - SearchRequest searchRequest = new SearchRequest(alias, dataTypeName); - searchRequest.setQuery(queryBuilder); - SearchResponse response = null; - try { - response = this.search(searchRequest,ignoreException); - total = response.getTotal(); - - } catch (IOException e) { - LOG.warn("error do search {}: {}", queryBuilder, e); - } - return new SearchResult(response != null ? response.getHits() : new SearchHit[] {}, total); - } - @Override - public @Nonnull SearchResult doReadAllJsonData(String dataTypeName) { - return this.doReadAllJsonData( dataTypeName,false); - } @Override - public @Nonnull SearchResult doReadAllJsonData( String dataTypeName, boolean ignoreException) { - return doReadByQueryJsonData( dataTypeName, QueryBuilders.matchAllQuery(),ignoreException); - } - - public @Nonnull SearchResult doReadAllJsonData(String alias, String dataType, boolean ignoreException) { - return doReadByQueryJsonData( alias, dataType, QueryBuilders.matchAllQuery(),ignoreException); - } - @Override - public String doUpdateOrCreate(String dataTypeName, String esId, String json) { - return this.doUpdateOrCreate(dataTypeName, esId, json,null); - } - - - - @Override - public String doUpdateOrCreate(String dataTypeName, String esId, String json, List onlyForInsert) { - if(esId==null) { - LOG.warn("try to update or insert {} with id null is not allowed.",dataTypeName); - return null; - } - boolean success = false; - UpdateRequest request = new UpdateRequest(dataTypeName, dataTypeName, esId,this.doRefreshAfterWrite); - request.source(new JSONObject(json),onlyForInsert); - try { - UpdateResponse response = this.update(request); - success = response.succeeded(); - } catch (IOException e) { - LOG.warn("Problem updating {} with id {} and data {}: {}", dataTypeName, esId, json, e); - } -// if(this.doRefreshAfterWrite) { -// this.doRefresh(dataTypeName); -// } - return success ? esId : null; - } - @Override - public boolean doUpdate(String dataTypeName, String json, QueryBuilder query) { - boolean success = false; - UpdateByQueryRequest request = new UpdateByQueryRequest(dataTypeName, dataTypeName ,this.doRefreshAfterWrite); - request.source(new JSONObject(json),query); - try { - UpdateByQueryResponse response = this.update(request); - success = !response.hasFailures(); - } catch (IOException e) { - LOG.warn("Problem updating items in {} with query {} and data {}: {}", dataTypeName, query, json, e); - } -// if(this.doRefreshAfterWrite) { -// this.doRefresh(dataTypeName); -// } - return success; - } - - - - @Override - public int doRemove(String dataTypeName, QueryBuilder query) { - int del=0; - DeleteByQueryRequest request = new DeleteByQueryRequest(dataTypeName,this.doRefreshAfterWrite); - request.source(query); - try { - DeleteByQueryResponse response = this.deleteByQuery(request); - del = response.getDeleted(); - } catch (IOException e) { - LOG.warn("Problem delete in {} with query {}:{} ", dataTypeName, query.toJSON(), e); - } -// if(this.doRefreshAfterWrite) { -// this.doRefresh(dataTypeName); -// } - return del; - } - - + public @Nonnull SearchResult doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder, + boolean ignoreException) { + return this.doReadByQueryJsonData(dataTypeName, dataTypeName, queryBuilder, ignoreException); + } + + @Override + public @Nonnull SearchResult doReadByQueryJsonData(String alias, String dataTypeName, + QueryBuilder queryBuilder, boolean ignoreException) { + + long total = 0; + LOG.debug("NetworkIndex query and read: {}", dataTypeName); + + SearchRequest searchRequest = new SearchRequest(alias, dataTypeName); + searchRequest.setQuery(queryBuilder); + SearchResponse response = null; + try { + response = this.search(searchRequest, ignoreException); + total = response.getTotal(); + + } catch (IOException e) { + LOG.warn("error do search {}: {}", queryBuilder, e); + } + return new SearchResult(response != null ? response.getHits() : new SearchHit[] {}, total); + } + + @Override + public @Nonnull SearchResult doReadAllJsonData(String dataTypeName) { + return this.doReadAllJsonData(dataTypeName, false); + } + + @Override + public @Nonnull SearchResult doReadAllJsonData(String dataTypeName, boolean ignoreException) { + return doReadByQueryJsonData(dataTypeName, QueryBuilders.matchAllQuery(), ignoreException); + } + + public @Nonnull SearchResult doReadAllJsonData(String alias, String dataType, boolean ignoreException) { + return doReadByQueryJsonData(alias, dataType, QueryBuilders.matchAllQuery(), ignoreException); + } + + @Override + public String doUpdateOrCreate(String dataTypeName, String esId, String json) { + return this.doUpdateOrCreate(dataTypeName, esId, json, null); + } + + + + @Override + public String doUpdateOrCreate(String dataTypeName, String esId, String json, List onlyForInsert) { + if (esId == null) { + LOG.warn("try to update or insert {} with id null is not allowed.", dataTypeName); + return null; + } + boolean success = false; + UpdateRequest request = new UpdateRequest(dataTypeName, dataTypeName, esId, this.doRefreshAfterWrite); + request.source(new JSONObject(json), onlyForInsert); + try { + UpdateResponse response = this.update(request); + success = response.succeeded(); + } catch (IOException e) { + LOG.warn("Problem updating {} with id {} and data {}: {}", dataTypeName, esId, json, e); + } + // if(this.doRefreshAfterWrite) { + // this.doRefresh(dataTypeName); + // } + return success ? esId : null; + } + + @Override + public boolean doUpdate(String dataTypeName, String json, QueryBuilder query) { + boolean success = false; + UpdateByQueryRequest request = new UpdateByQueryRequest(dataTypeName, dataTypeName, this.doRefreshAfterWrite); + request.source(new JSONObject(json), query); + try { + UpdateByQueryResponse response = this.update(request); + success = !response.hasFailures(); + } catch (IOException e) { + LOG.warn("Problem updating items in {} with query {} and data {}: {}", dataTypeName, query, json, e); + } + // if(this.doRefreshAfterWrite) { + // this.doRefresh(dataTypeName); + // } + return success; + } + + + + @Override + public int doRemove(String dataTypeName, QueryBuilder query) { + int del = 0; + DeleteByQueryRequest request = new DeleteByQueryRequest(dataTypeName, this.doRefreshAfterWrite); + request.source(query); + try { + DeleteByQueryResponse response = this.deleteByQuery(request); + del = response.getDeleted(); + } catch (IOException e) { + LOG.warn("Problem delete in {} with query {}:{} ", dataTypeName, query.toJSON(), e); + } + // if(this.doRefreshAfterWrite) { + // this.doRefresh(dataTypeName); + // } + return del; + } + + } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/IsEsObject.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/IsEsObject.java index 7dc6be372..e18eabcd3 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/IsEsObject.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/IsEsObject.java @@ -28,12 +28,14 @@ public interface IsEsObject { /** * Set the ES Id + * * @param id Set the ID, created by ES for this Object */ - void setEsId( String id ); + void setEsId(String id); /** * Get Id content as string that is used in ES + * * @return Related ID, that was specified by set command. */ String getEsId(); diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/Portstatus.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/Portstatus.java index ed6c95fd2..250842e57 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/Portstatus.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/Portstatus.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.database; @@ -58,11 +58,11 @@ public class Portstatus { public static boolean isAvailable(HostInfo... hosts) { for (HostInfo host : hosts) { - if (!isAvailable(host.hostname, host.port)) { - return false; - } - } - return true; + if (!isAvailable(host.hostname, host.port)) { + return false; + } + } + return true; } public static boolean waitSecondsTillAvailable(long timeoutSeconds, HostInfo... hosts) { @@ -72,7 +72,7 @@ public class Portstatus { } long waitSeconds = 0; boolean res = false; - while ( (timeoutSeconds == 0 || ++waitSeconds < timeoutSeconds) && !(res = isAvailable(hosts))) { + while ((timeoutSeconds == 0 || ++waitSeconds < timeoutSeconds) && !(res = isAvailable(hosts))) { try { Thread.sleep(1000); } catch (InterruptedException e) { @@ -82,7 +82,7 @@ public class Portstatus { return res; } - public static boolean waitSecondsTillAvailable(long timeoutSeconds, String dnsName, int port ) { + public static boolean waitSecondsTillAvailable(long timeoutSeconds, String dnsName, int port) { return waitSecondsTillAvailable(timeoutSeconds, new HostInfo(dnsName, port)); } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java index 749714b48..4c4c41437 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchHit.java @@ -33,7 +33,7 @@ public class SearchHit { public SearchHit(JSONObject o) { this.raw = o; - this.index=o.getString("_index"); + this.index = o.getString("_index"); this.type = o.getString("_type"); this.id = o.getString("_id"); this.source = o.getJSONObject("_source"); @@ -42,9 +42,11 @@ public class SearchHit { public String getIndex() { return this.index; } + public String getType() { return this.type; } + public String getId() { return this.id; } @@ -52,9 +54,11 @@ public class SearchHit { public JSONObject getSource() { return this.source; } + public String getSourceAsString() { return this.source.toString(); } + public JSONObject getRaw() { return this.raw; } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchResult.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchResult.java index 5dc6115c8..5a011eec9 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchResult.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/SearchResult.java @@ -27,41 +27,46 @@ import java.util.List; public class SearchResult { - /** - * objects in results - */ - private final List hits; - /** - * size of all potential hits - * not necessarily the number of hits - */ - private long total; + /** + * objects in results + */ + private final List hits; + /** + * size of all potential hits not necessarily the number of hits + */ + private long total; - public SearchResult(T[] hits) { - this(hits,hits==null?0:hits.length); - } - public SearchResult(T[] hits,long total) { - this.hits = Arrays.asList(hits); - this.total = total; - } -// public SearchResult(List hits,long total) { -// this.hits = hits; -// this.total = total; -// } - public SearchResult() { - this.hits=new ArrayList<>(); - this.total = 0; - } - public List getHits() { - return this.hits; - } - public long getTotal() { - return this.total; - } - public void setTotal(long total) { - this.total = total; - } - public void add(T object) { - this.hits.add(object); - } + public SearchResult(T[] hits) { + this(hits, hits == null ? 0 : hits.length); + } + + public SearchResult(T[] hits, long total) { + this.hits = Arrays.asList(hits); + this.total = total; + } + + // public SearchResult(List hits,long total) { + // this.hits = hits; + // this.total = total; + // } + public SearchResult() { + this.hits = new ArrayList<>(); + this.total = 0; + } + + public List getHits() { + return this.hits; + } + + public long getTotal() { + return this.total; + } + + public void setTotal(long total) { + this.total = total; + } + + public void add(T object) { + this.hits.add(object); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/config/HostInfo.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/config/HostInfo.java index 858807863..cb0454361 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/config/HostInfo.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/config/HostInfo.java @@ -27,80 +27,83 @@ import java.util.regex.Pattern; public class HostInfo { - public enum Protocol{ - HTTP("http"), - HTTPS("https");//, -// FILETRANSFERPROTOCOL("ftp"); - - private final String value; - - private Protocol(String s) { - this.value = s; - } - @Override - public String toString() { - return this.value; - } - public String getValue() { - return value; - } - public static Protocol getValueOf(String s) { - s = s.toLowerCase(); - for(Protocol p:Protocol.values()) { - if(p.value.equals(s)) { - return p; - } - } - return HTTP; - } - } - private static final Protocol DEFAULT_PROTOCOL = Protocol.HTTP; - public final String hostname; - public final int port; - public final Protocol protocol; - - public HostInfo(String hostname,int port, Protocol protocol) { - this.hostname = hostname; - this.port = port; - this.protocol=protocol; - - } - - public HostInfo(String hostname, int port) { - this(hostname,port,DEFAULT_PROTOCOL); - - } - - @Override - public String toString() { - return "HostInfo [hostname=" + hostname + ", port=" + port + ", protocol=" + protocol + "]"; - } - - public String toUrl() { - return String.format("%s://%s:%d",this.protocol,this.hostname,this.port); - } - - public static HostInfo getDefault() { - return new HostInfo("localhost",9200,Protocol.HTTP); - } - - /** - * @param dbUrl - * @return - */ - public static HostInfo parse(String dbUrl) throws ParseException{ - final String regex = "^(https?):\\/\\/([^:]*):?([0-9]{0,5})$"; - final Pattern pattern = Pattern.compile(regex); - final Matcher matcher = pattern.matcher(dbUrl); - if(!matcher.find() || matcher.groupCount()<2) { - throw new ParseException("url "+dbUrl+" not parseable", 0); - } - Protocol p = Protocol.getValueOf(matcher.group(1)); - String host = matcher.group(2); - int port = p==Protocol.HTTP?80:443; - if(matcher.groupCount()>2) { - port=Integer.parseInt(matcher.group(3)); - } - return new HostInfo(host,port,p); - } + public enum Protocol { + HTTP("http"), HTTPS("https");//, + // FILETRANSFERPROTOCOL("ftp"); + + private final String value; + + private Protocol(String s) { + this.value = s; + } + + @Override + public String toString() { + return this.value; + } + + public String getValue() { + return value; + } + + public static Protocol getValueOf(String s) { + s = s.toLowerCase(); + for (Protocol p : Protocol.values()) { + if (p.value.equals(s)) { + return p; + } + } + return HTTP; + } + } + + private static final Protocol DEFAULT_PROTOCOL = Protocol.HTTP; + public final String hostname; + public final int port; + public final Protocol protocol; + + public HostInfo(String hostname, int port, Protocol protocol) { + this.hostname = hostname; + this.port = port; + this.protocol = protocol; + + } + + public HostInfo(String hostname, int port) { + this(hostname, port, DEFAULT_PROTOCOL); + + } + + @Override + public String toString() { + return "HostInfo [hostname=" + hostname + ", port=" + port + ", protocol=" + protocol + "]"; + } + + public String toUrl() { + return String.format("%s://%s:%d", this.protocol, this.hostname, this.port); + } + + public static HostInfo getDefault() { + return new HostInfo("localhost", 9200, Protocol.HTTP); + } + + /** + * @param dbUrl + * @return + */ + public static HostInfo parse(String dbUrl) throws ParseException { + final String regex = "^(https?):\\/\\/([^:]*):?([0-9]{0,5})$"; + final Pattern pattern = Pattern.compile(regex); + final Matcher matcher = pattern.matcher(dbUrl); + if (!matcher.find() || matcher.groupCount() < 2) { + throw new ParseException("url " + dbUrl + " not parseable", 0); + } + Protocol p = Protocol.getValueOf(matcher.group(1)); + String host = matcher.group(2); + int port = p == Protocol.HTTP ? 80 : 443; + if (matcher.groupCount() > 2) { + port = Integer.parseInt(matcher.group(3)); + } + return new HostInfo(host, port, p); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntry.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntry.java index 1c1c4ecd3..d55e66d2e 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntry.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntry.java @@ -30,24 +30,27 @@ import java.util.regex.Pattern; * */ public class AliasesEntry { - private static final String regex = "^([^\\ ]+)[\\ ]+([^\\ ]+)[\\ ]+.*$"; - private static final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); + private static final String regex = "^([^\\ ]+)[\\ ]+([^\\ ]+)[\\ ]+.*$"; + private static final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); - - public String getAlias() { - return alias; - } - public String getIndex() { - return index; - } - private final String alias; - private final String index; - public AliasesEntry(String line) throws ParseException { - final Matcher matcher = pattern.matcher(line); - if (!matcher.find() || matcher.groupCount() < 2) { - throw new ParseException("unable to parse string:" + line, 0); - } - this.alias = matcher.group(1); - this.index = matcher.group(2); - } + + public String getAlias() { + return alias; + } + + public String getIndex() { + return index; + } + + private final String alias; + private final String index; + + public AliasesEntry(String line) throws ParseException { + final Matcher matcher = pattern.matcher(line); + if (!matcher.find() || matcher.groupCount() < 2) { + throw new ParseException("unable to parse string:" + line, 0); + } + this.alias = matcher.group(1); + this.index = matcher.group(2); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntryList.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntryList.java index 3891ecfb7..e00ba5d4c 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntryList.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/AliasesEntryList.java @@ -28,35 +28,35 @@ import java.util.List; * @author Michael Dürre * */ -public class AliasesEntryList extends ArrayList{ +public class AliasesEntryList extends ArrayList { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * @param alias - * @return - */ - public AliasesEntry findByAlias(String alias) { - for(AliasesEntry e:this) { - if(e.getAlias().equals(alias)) { - return e; - } - } - return null; - } + /** + * @param alias + * @return + */ + public AliasesEntry findByAlias(String alias) { + for (AliasesEntry e : this) { + if (e.getAlias().equals(alias)) { + return e; + } + } + return null; + } - /** - * @return - */ - public List getLinkedIndices() { - List list = new ArrayList(); - for(AliasesEntry e:this) { - list.add(e.getIndex()); - } - return list; - } + /** + * @return + */ + public List getLinkedIndices() { + List list = new ArrayList(); + for (AliasesEntry e : this) { + list.add(e.getIndex()); + } + return list; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/DbFilter.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/DbFilter.java index 082a28817..2a8f04df3 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/DbFilter.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/DbFilter.java @@ -25,42 +25,42 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.queries.RangeQueryBuilder public class DbFilter { - public static String createDatabaseRegex(String restFilterValue) { - return restFilterValue == null ? null : restFilterValue.replace("?", ".{1,1}").replace("*", ".*"); - } + public static String createDatabaseRegex(String restFilterValue) { + return restFilterValue == null ? null : restFilterValue.replace("?", ".{1,1}").replace("*", ".*"); + } - public static boolean hasSearchParams(String restFilterValue) { - return restFilterValue == null ? false : restFilterValue.contains("*") || restFilterValue.contains("?"); - } + public static boolean hasSearchParams(String restFilterValue) { + return restFilterValue == null ? false : restFilterValue.contains("*") || restFilterValue.contains("?"); + } - public static boolean isComparisonValid(String restFilterValue) { - return restFilterValue == null ? false : restFilterValue.contains(">") || restFilterValue.contains("<"); - } + public static boolean isComparisonValid(String restFilterValue) { + return restFilterValue == null ? false : restFilterValue.contains(">") || restFilterValue.contains("<"); + } - public static RangeQueryBuilder getRangeQuery(String key, String restFilterValue) { - RangeQueryBuilder query = new RangeQueryBuilder(key); - restFilterValue = restFilterValue.trim(); - if (restFilterValue.startsWith(">=")) { - query.gte(getObjectFromString(restFilterValue.substring(2).trim())); - } else if (restFilterValue.startsWith(">")) { - query.gt(getObjectFromString(restFilterValue.substring(1).trim())); - } else if (restFilterValue.startsWith("<=")) { - query.lte(getObjectFromString(restFilterValue.substring(2).trim())); - } else if (restFilterValue.startsWith("<")) { - query.lt(getObjectFromString(restFilterValue.substring(1).trim())); - } else { - return null; - } + public static RangeQueryBuilder getRangeQuery(String key, String restFilterValue) { + RangeQueryBuilder query = new RangeQueryBuilder(key); + restFilterValue = restFilterValue.trim(); + if (restFilterValue.startsWith(">=")) { + query.gte(getObjectFromString(restFilterValue.substring(2).trim())); + } else if (restFilterValue.startsWith(">")) { + query.gt(getObjectFromString(restFilterValue.substring(1).trim())); + } else if (restFilterValue.startsWith("<=")) { + query.lte(getObjectFromString(restFilterValue.substring(2).trim())); + } else if (restFilterValue.startsWith("<")) { + query.lt(getObjectFromString(restFilterValue.substring(1).trim())); + } else { + return null; + } - return query; - } + return query; + } - private static Object getObjectFromString(String str) { - try { - return Double.parseDouble(str); - } catch (NumberFormatException | NullPointerException nfe) { - return str; - } - - } + private static Object getObjectFromString(String str) { + try { + return Double.parseDouble(str); + } catch (NumberFormatException | NullPointerException nfe) { + return str; + } + + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/EsVersion.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/EsVersion.java index d99e0e701..7d106dfec 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/EsVersion.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/EsVersion.java @@ -31,109 +31,108 @@ import org.eclipse.jdt.annotation.NonNull; * */ public class EsVersion { - - private final String raw; - private final int major; - private final int minor; - private final int revision; - - public EsVersion(@NonNull String version) throws ParseException { - String[] hlp=version.split("\\."); - if(hlp.length<3) { - throw new ParseException("unable to parse version string: "+version, 0); - } - this.raw = version; - this.major = Integer.parseInt(hlp[0]); - this.minor = Integer.parseInt(hlp[1]); - this.revision = Integer.parseInt(hlp[2]); - } - /** - * @param major - * @param minor - * @param revision - */ - public EsVersion(int major, int minor, int revision) { - this.raw = String.format("%d.%d.%d", major,minor,revision); - this.major = major; - this.minor = minor; - this.revision = revision; - } + private final String raw; + private final int major; + private final int minor; + private final int revision; - /** - * @return the revision - */ - public int getRevision() { - return revision; - } + public EsVersion(@NonNull String version) throws ParseException { + String[] hlp = version.split("\\."); + if (hlp.length < 3) { + throw new ParseException("unable to parse version string: " + version, 0); + } + this.raw = version; + this.major = Integer.parseInt(hlp[0]); + this.minor = Integer.parseInt(hlp[1]); + this.revision = Integer.parseInt(hlp[2]); + } - /** - * @return the minor - */ - public int getMinor() { - return minor; - } + /** + * @param major + * @param minor + * @param revision + */ + public EsVersion(int major, int minor, int revision) { + this.raw = String.format("%d.%d.%d", major, minor, revision); + this.major = major; + this.minor = minor; + this.revision = revision; + } - /** - * @return the major - */ - public int getMajor() { - return major; - } + /** + * @return the revision + */ + public int getRevision() { + return revision; + } + + /** + * @return the minor + */ + public int getMinor() { + return minor; + } + + /** + * @return the major + */ + public int getMajor() { + return major; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof EsVersion)) { + return false; + } + EsVersion esobj = (EsVersion) obj; + return this.major == esobj.major && this.minor == esobj.minor && this.revision == esobj.revision; + } + + @Override + public int hashCode() { + return this.raw.hashCode(); + } + + public boolean isNewerOrEqualThan(EsVersion v) { + if (this.equals(v)) { + return true; + } + if (this.major > v.major) { + return true; + } else if (this.major < v.major) { + return false; + } + if (this.minor > v.minor) { + return true; + } else if (this.minor < v.minor) { + return false; + } + if (this.revision > v.revision) { + return true; + } + return false; + } + + public boolean isOlderOrEqualThan(EsVersion v) { + if (this.equals(v)) { + return true; + } + if (this.major < v.major) { + return true; + } else if (this.major > v.major) { + return false; + } + if (this.minor < v.minor) { + return true; + } else if (this.minor > v.minor) { + return false; + } + if (this.revision < v.revision) { + return true; + } + return false; + } - @Override - public boolean equals(Object obj) { - if(!(obj instanceof EsVersion)) { - return false; - } - EsVersion esobj = (EsVersion)obj; - return this.major==esobj.major && this.minor==esobj.minor && this.revision==esobj.revision; - } - @Override - public int hashCode() { - return this.raw.hashCode(); - } - public boolean isNewerOrEqualThan(EsVersion v) { - if(this.equals(v)) { - return true; - } - if(this.major>v.major) { - return true; - } - else if(this.majorv.minor) { - return true; - } - else if(this.minorv.revision) { - return true; - } - return false; - } - public boolean isOlderOrEqualThan(EsVersion v) { - if(this.equals(v)) { - return true; - } - if(this.majorv.major) { - return false; - } - if(this.minorv.minor) { - return false; - } - if(this.revision{ +public class IndicesEntryList extends ArrayList { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * @param index - * @return - */ - public IndicesEntry findByIndex(String index) { - for(IndicesEntry e:this) { - if(e.getName().equals(index)) { - return e; - } - } - return null; - } + /** + * @param index + * @return + */ + public IndicesEntry findByIndex(String index) { + for (IndicesEntry e : this) { + if (e.getName().equals(index)) { + return e; + } + } + return null; + } - /** - * @param indices - * @return - */ - public IndicesEntryList subList(List indices) { - IndicesEntryList sublist = new IndicesEntryList(); - for(IndicesEntry e:this) { - if(indices.contains(e.getName())) { - sublist.add(e); - } - } - return sublist; - } + /** + * @param indices + * @return + */ + public IndicesEntryList subList(List indices) { + IndicesEntryList sublist = new IndicesEntryList(); + for (IndicesEntry e : this) { + if (indices.contains(e.getName())) { + sublist.add(e); + } + } + return sublist; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/BoolQueryBuilder.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/BoolQueryBuilder.java index b362c4684..359b9d04b 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/BoolQueryBuilder.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/BoolQueryBuilder.java @@ -26,67 +26,67 @@ import org.json.JSONObject; public class BoolQueryBuilder extends QueryBuilder { - private JSONObject inner; + private JSONObject inner; - public BoolQueryBuilder() { - super(); - this.inner = new JSONObject(); - this.setQuery("bool", this.inner); - } + public BoolQueryBuilder() { + super(); + this.inner = new JSONObject(); + this.setQuery("bool", this.inner); + } - @Override - public String toString() { - return "BoolQueryBuilder [inner=" + inner + "]"; - } + @Override + public String toString() { + return "BoolQueryBuilder [inner=" + inner + "]"; + } - public static boolean isEmpty(JSONObject o) { - return o.keySet().size() <= 0; - } + public static boolean isEmpty(JSONObject o) { + return o.keySet().size() <= 0; + } - public BoolQueryBuilder must(QueryBuilder query) { + public BoolQueryBuilder must(QueryBuilder query) { - if (!isEmpty(this.inner)) { - Object x = this.inner.has("must") ? this.inner.get("must") : this.inner; - if (x instanceof JSONArray) { - ((JSONArray) x).put(query.getInner()); - } else { - this.inner = new JSONObject(); - this.inner.put("must", new JSONObject()); - JSONArray a = new JSONArray(); - a.put(x); - a.put(query.getInner()); - this.inner.put("must", a); - } - } else { - this.inner.put("must", query.getInner()); - } - this.setQuery("bool", this.inner); - return this; - } + if (!isEmpty(this.inner)) { + Object x = this.inner.has("must") ? this.inner.get("must") : this.inner; + if (x instanceof JSONArray) { + ((JSONArray) x).put(query.getInner()); + } else { + this.inner = new JSONObject(); + this.inner.put("must", new JSONObject()); + JSONArray a = new JSONArray(); + a.put(x); + a.put(query.getInner()); + this.inner.put("must", a); + } + } else { + this.inner.put("must", query.getInner()); + } + this.setQuery("bool", this.inner); + return this; + } - /** - * @param query - */ - public BoolQueryBuilder should(QueryBuilder query) { - if (!isEmpty(this.inner)) { - Object x = this.inner.has("should") ? this.inner.get("should") : this.inner; - if (x instanceof JSONArray) { - ((JSONArray) x).put(query.getInner()); - } else { - this.inner = new JSONObject(); - // this.inner.put("should", new JSONObject()); - JSONArray a = new JSONArray(); - if (!x.toString().equals("{}")) { - a.put(x); - } - a.put(query.getInner()); - this.inner.put("should", a); - } - } else { - this.inner.put("should", query.getInner()); - } - this.setQuery("bool", this.inner); - return this; - } + /** + * @param query + */ + public BoolQueryBuilder should(QueryBuilder query) { + if (!isEmpty(this.inner)) { + Object x = this.inner.has("should") ? this.inner.get("should") : this.inner; + if (x instanceof JSONArray) { + ((JSONArray) x).put(query.getInner()); + } else { + this.inner = new JSONObject(); + // this.inner.put("should", new JSONObject()); + JSONArray a = new JSONArray(); + if (!x.toString().equals("{}")) { + a.put(x); + } + a.put(query.getInner()); + this.inner.put("should", a); + } + } else { + this.inner.put("should", query.getInner()); + } + this.setQuery("bool", this.inner); + return this; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilder.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilder.java index ad6c199ea..519502efd 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilder.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilder.java @@ -26,76 +26,78 @@ import org.json.JSONObject; public class QueryBuilder { - private JSONObject innerQuery; - private final JSONObject outerQuery; - private final JSONObject queryObj; + private JSONObject innerQuery; + private final JSONObject outerQuery; + private final JSONObject queryObj; - public QueryBuilder() { - this.outerQuery = new JSONObject(); - this.queryObj = new JSONObject(); - this.outerQuery.put("query", this.queryObj); + public QueryBuilder() { + this.outerQuery = new JSONObject(); + this.queryObj = new JSONObject(); + this.outerQuery.put("query", this.queryObj); - } + } - public QueryBuilder from(long from) { - this.outerQuery.put("from", from); - return this; - } + public QueryBuilder from(long from) { + this.outerQuery.put("from", from); + return this; + } - public QueryBuilder size(long size) { - this.outerQuery.put("size", size); - return this; - } + public QueryBuilder size(long size) { + this.outerQuery.put("size", size); + return this; + } - public QueryBuilder sort(String prop, SortOrder order) { - JSONArray a; - if (this.outerQuery.has("sort")) { - a = this.outerQuery.getJSONArray("sort"); - } else { - a = new JSONArray(); - } - JSONObject sortObj = new JSONObject(); - JSONObject orderObj = new JSONObject(); - orderObj.put("order", order.getValue()); - sortObj.put(prop, orderObj); - a.put(sortObj); - this.outerQuery.put("sort", a); - return this; - } + public QueryBuilder sort(String prop, SortOrder order) { + JSONArray a; + if (this.outerQuery.has("sort")) { + a = this.outerQuery.getJSONArray("sort"); + } else { + a = new JSONArray(); + } + JSONObject sortObj = new JSONObject(); + JSONObject orderObj = new JSONObject(); + orderObj.put("order", order.getValue()); + sortObj.put(prop, orderObj); + a.put(sortObj); + this.outerQuery.put("sort", a); + return this; + } - public QueryBuilder aggregations(String key, SortOrder sortOrder) { - JSONObject keyquery = new JSONObject(); - JSONObject terms = new JSONObject(); - JSONObject field = new JSONObject(); - field.put("field", key); - terms.put("terms", field); - if(sortOrder!=null) { - JSONObject so = new JSONObject(); - so.put("_key",sortOrder.getValue()); - terms.put("order", so); - } - keyquery.put(key, terms); - this.outerQuery.put("aggs", keyquery); - return this; - } + public QueryBuilder aggregations(String key, SortOrder sortOrder) { + JSONObject keyquery = new JSONObject(); + JSONObject terms = new JSONObject(); + JSONObject field = new JSONObject(); + field.put("field", key); + terms.put("terms", field); + if (sortOrder != null) { + JSONObject so = new JSONObject(); + so.put("_key", sortOrder.getValue()); + terms.put("order", so); + } + keyquery.put(key, terms); + this.outerQuery.put("aggs", keyquery); + return this; + } - protected QueryBuilder setQuery(String key, JSONObject query) { - this.innerQuery = query; - this.queryObj.put(key, this.innerQuery); - return this; - } + protected QueryBuilder setQuery(String key, JSONObject query) { + this.innerQuery = query; + this.queryObj.put(key, this.innerQuery); + return this; + } - public JSONObject getInner() { - return this.queryObj; - } - public boolean contains(String match) { - return this.toJSON().contains(match); - } - public String toJSON() { - return this.outerQuery.toString(); - } + public JSONObject getInner() { + return this.queryObj; + } - public QueryBuilder aggregations(String key) { - return this.aggregations(key, null); - } + public boolean contains(String match) { + return this.toJSON().contains(match); + } + + public String toJSON() { + return this.outerQuery.toString(); + } + + public QueryBuilder aggregations(String key) { + return this.aggregations(key, null); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilders.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilders.java index 4d5b20037..7b22fd5e7 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilders.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/QueryBuilders.java @@ -25,36 +25,42 @@ import org.json.JSONObject; public class QueryBuilders { - public static QueryBuilder matchAllQuery() { - return new QueryBuilder().setQuery("match_all",new JSONObject()); - } - public static QueryBuilder termQuery(String key, String value) { - JSONObject o=new JSONObject(); - o.put(key, value); - return new QueryBuilder().setQuery("term", o); - } - public static QueryBuilder matchQuery(String key, Object value) { - JSONObject o=new JSONObject(); - o.put(key, value); - return new QueryBuilder().setQuery("match", o); - } - public static BoolQueryBuilder boolQuery() { - return new BoolQueryBuilder(); - } - public static RangeQueryBuilder rangeQuery(String key) { - return new RangeQueryBuilder(key); - } - public static RegexQueryBuilder regex(String propertyName, String re) { - return new RegexQueryBuilder().add(propertyName, re); - } - /** - * @param object - * @return - */ - public static QueryBuilder searchAllFieldsQuery(String filter) { - JSONObject inner = new JSONObject(); - inner.put("default_field", "*"); - inner.put("query", filter==null?"":filter); - return new QueryBuilder().setQuery("query_string", inner); - } + public static QueryBuilder matchAllQuery() { + return new QueryBuilder().setQuery("match_all", new JSONObject()); + } + + public static QueryBuilder termQuery(String key, String value) { + JSONObject o = new JSONObject(); + o.put(key, value); + return new QueryBuilder().setQuery("term", o); + } + + public static QueryBuilder matchQuery(String key, Object value) { + JSONObject o = new JSONObject(); + o.put(key, value); + return new QueryBuilder().setQuery("match", o); + } + + public static BoolQueryBuilder boolQuery() { + return new BoolQueryBuilder(); + } + + public static RangeQueryBuilder rangeQuery(String key) { + return new RangeQueryBuilder(key); + } + + public static RegexQueryBuilder regex(String propertyName, String re) { + return new RegexQueryBuilder().add(propertyName, re); + } + + /** + * @param object + * @return + */ + public static QueryBuilder searchAllFieldsQuery(String filter) { + JSONObject inner = new JSONObject(); + inner.put("default_field", "*"); + inner.put("query", filter == null ? "" : filter); + return new QueryBuilder().setQuery("query_string", inner); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RangeQueryBuilder.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RangeQueryBuilder.java index 6977380ad..e8b3d3047 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RangeQueryBuilder.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RangeQueryBuilder.java @@ -23,67 +23,69 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.queries; import org.json.JSONObject; -public class RangeQueryBuilder extends QueryBuilder{ +public class RangeQueryBuilder extends QueryBuilder { - private Object gtValue=null; - private Object gteValue=null; - private Float boost=2.0f; - private Object ltValue=null; - private Object lteValue=null; - private String key; + private Object gtValue = null; + private Object gteValue = null; + private Float boost = 2.0f; + private Object ltValue = null; + private Object lteValue = null; + private String key; - public RangeQueryBuilder(String key) { - super(); - this.key=key; - - } + public RangeQueryBuilder(String key) { + super(); + this.key = key; - private void setQuery() { - JSONObject r=new JSONObject(); - JSONObject k=new JSONObject(); - if(this.gteValue!=null) { - k.put("gte", this.gteValue); - }else if(this.gtValue!=null) { - k.put("gt", this.gtValue); - } - if(this.lteValue!=null) { - k.put("lte", this.lteValue); - } else if(this.ltValue!=null) { - k.put("lt", this.ltValue); - } - if(this.boost!=null) { - k.put("boost", this.boost); - } - r.put(this.key,k); - - this.setQuery("range",r); - } - + } - public RangeQueryBuilder lte(Object compare) { - this.lteValue=compare; - this.ltValue=null; - this.setQuery(); - return this; - } - public RangeQueryBuilder lt(Object compare) { - this.lteValue=null; - this.ltValue=compare; - this.setQuery(); - return this; - } - - public RangeQueryBuilder gte(Object compare) { - this.gteValue=compare; - this.gtValue=null; - this.setQuery(); - return this; - } - public RangeQueryBuilder gt(Object compare) { - this.gteValue=null; - this.gtValue=compare; - this.setQuery(); - return this; - } + private void setQuery() { + JSONObject r = new JSONObject(); + JSONObject k = new JSONObject(); + if (this.gteValue != null) { + k.put("gte", this.gteValue); + } else if (this.gtValue != null) { + k.put("gt", this.gtValue); + } + if (this.lteValue != null) { + k.put("lte", this.lteValue); + } else if (this.ltValue != null) { + k.put("lt", this.ltValue); + } + if (this.boost != null) { + k.put("boost", this.boost); + } + r.put(this.key, k); + + this.setQuery("range", r); + } + + + public RangeQueryBuilder lte(Object compare) { + this.lteValue = compare; + this.ltValue = null; + this.setQuery(); + return this; + } + + public RangeQueryBuilder lt(Object compare) { + this.lteValue = null; + this.ltValue = compare; + this.setQuery(); + return this; + } + + public RangeQueryBuilder gte(Object compare) { + this.gteValue = compare; + this.gtValue = null; + this.setQuery(); + return this; + } + + public RangeQueryBuilder gt(Object compare) { + this.gteValue = null; + this.gtValue = compare; + this.setQuery(); + return this; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RegexQueryBuilder.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RegexQueryBuilder.java index 1df10ff56..d2002e506 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RegexQueryBuilder.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/RegexQueryBuilder.java @@ -25,23 +25,25 @@ import org.json.JSONObject; public class RegexQueryBuilder extends QueryBuilder { - private JSONObject inner; + private JSONObject inner; - public RegexQueryBuilder() { - super(); - this.inner = new JSONObject(); - this.setQuery("regexp", this.inner); - } - public RegexQueryBuilder add(String propertyName, String filter) { - JSONObject regexFilter = new JSONObject(); - regexFilter.put("value", filter); - regexFilter.put("flags", "ALL"); - regexFilter.put("max_determinized_states", 10000); - this.inner.put(propertyName, regexFilter); - return this; - } - @Override - public String toString() { - return "RegexQueryBuilder [inner=" + inner + "]"; - } + public RegexQueryBuilder() { + super(); + this.inner = new JSONObject(); + this.setQuery("regexp", this.inner); + } + + public RegexQueryBuilder add(String propertyName, String filter) { + JSONObject regexFilter = new JSONObject(); + regexFilter.put("value", filter); + regexFilter.put("flags", "ALL"); + regexFilter.put("max_determinized_states", 10000); + this.inner.put(propertyName, regexFilter); + return this; + } + + @Override + public String toString() { + return "RegexQueryBuilder [inner=" + inner + "]"; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/SortOrder.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/SortOrder.java index 3c1bbf796..7647445ee 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/SortOrder.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/queries/SortOrder.java @@ -23,15 +23,15 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.queries; public enum SortOrder { - ASCENDING("asc"), - DESCENDING("desc"); - - private final String value; + ASCENDING("asc"), DESCENDING("desc"); - SortOrder(String so){ - this.value=so; - } - public String getValue() { - return this.value; - } + private final String value; + + SortOrder(String so) { + this.value = so; + } + + public String getValue() { + return this.value; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/BaseRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/BaseRequest.java index e7261f3e5..028de75d2 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/BaseRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/BaseRequest.java @@ -33,76 +33,77 @@ import org.slf4j.LoggerFactory; public abstract class BaseRequest { - private static final Logger LOG = LoggerFactory.getLogger(BaseRequest.class); - - public static final int DEFAULT_RETRIES = 1; - - protected final Request request; - private String query; - private final boolean refresh; - - public BaseRequest(String method, String endpoint) { - LOG.debug("create request {} {}" ,method, endpoint); - this.refresh = false; - this.request = new Request(method, endpoint); - query = null; - } - - public BaseRequest(String method, String endpoint, boolean refresh) { - LOG.debug("create request {} {} with refresh={}", method, endpoint, refresh); - this.refresh = refresh; - this.request = new Request(method, String.format("%s?refresh=%s", endpoint, String.valueOf(refresh))); - query = null; - } - - public BaseRequest(String method, String endpoint, boolean refresh, int retries) { - LOG.debug("create request {} {} with refresh={}", method, endpoint, refresh); - this.refresh = refresh; - this.request = new Request(method, String.format("%s?refresh=%s&retry_on_conflict=%d", endpoint, String.valueOf(refresh),retries)); - query = null; - } - - public Request getInner() { - - return this.request; - } - - public static String urlEncodeValue(String value) { - if (value == null) - return null; - try { - return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()).replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - LOG.warn("encoding problem: {}", ex.getMessage()); - } - return value; - } - - @Override - public String toString() { - return this.request.getMethod() + " " + this.request.getEndpoint() + " : " - + (this.query != null ? this.query : "no query"); - } - - protected void setQuery(QueryBuilder query) { - this.setQuery(query.toJSON()); - } - - public void setQuery(JSONObject o) { - this.setQuery(o.toString()); - } - - public void setQuery(String content) { - this.query = content; - LOG.trace("query={}", content); - this.request.setJsonEntity(this.query); - } - - protected String getQuery() { - return this.query; - } - - protected boolean doRefresh() { - return this.refresh; - } + private static final Logger LOG = LoggerFactory.getLogger(BaseRequest.class); + + public static final int DEFAULT_RETRIES = 1; + + protected final Request request; + private String query; + private final boolean refresh; + + public BaseRequest(String method, String endpoint) { + LOG.debug("create request {} {}", method, endpoint); + this.refresh = false; + this.request = new Request(method, endpoint); + query = null; + } + + public BaseRequest(String method, String endpoint, boolean refresh) { + LOG.debug("create request {} {} with refresh={}", method, endpoint, refresh); + this.refresh = refresh; + this.request = new Request(method, String.format("%s?refresh=%s", endpoint, String.valueOf(refresh))); + query = null; + } + + public BaseRequest(String method, String endpoint, boolean refresh, int retries) { + LOG.debug("create request {} {} with refresh={}", method, endpoint, refresh); + this.refresh = refresh; + this.request = new Request(method, + String.format("%s?refresh=%s&retry_on_conflict=%d", endpoint, String.valueOf(refresh), retries)); + query = null; + } + + public Request getInner() { + + return this.request; + } + + public static String urlEncodeValue(String value) { + if (value == null) + return null; + try { + return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()).replace("+", "%20"); + } catch (UnsupportedEncodingException ex) { + LOG.warn("encoding problem: {}", ex.getMessage()); + } + return value; + } + + @Override + public String toString() { + return this.request.getMethod() + " " + this.request.getEndpoint() + " : " + + (this.query != null ? this.query : "no query"); + } + + protected void setQuery(QueryBuilder query) { + this.setQuery(query.toJSON()); + } + + public void setQuery(JSONObject o) { + this.setQuery(o.toString()); + } + + public void setQuery(String content) { + this.query = content; + LOG.trace("query={}", content); + this.request.setJsonEntity(this.query); + } + + protected String getQuery() { + return this.query; + } + + protected boolean doRefresh() { + return this.refresh; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterHealthRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterHealthRequest.java index 4b837c823..e357c416b 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterHealthRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterHealthRequest.java @@ -21,15 +21,15 @@ */ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; -public class ClusterHealthRequest extends BaseRequest{ +public class ClusterHealthRequest extends BaseRequest { - - public ClusterHealthRequest() { - super("GET","/_cluster/health"); - } - public void timeout(long seconds) { - this.request.addParameter("timeout", String.valueOf(seconds)+"s"); - - } + public ClusterHealthRequest() { + super("GET", "/_cluster/health"); + } + + public void timeout(long seconds) { + this.request.addParameter("timeout", String.valueOf(seconds) + "s"); + + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterSettingsRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterSettingsRequest.java index cc2d972b5..1379da5ad 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterSettingsRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ClusterSettingsRequest.java @@ -25,26 +25,27 @@ import org.json.JSONObject; //https://www.elastic.co/guide/en/elasticsearch/reference/6.8/docs-index_.html //https://github.com/elastic/elasticsearch/blob/6.8/rest-api-spec/src/main/resources/rest-api-spec/api/cluster.put_settings.json -public class ClusterSettingsRequest extends BaseRequest{ +public class ClusterSettingsRequest extends BaseRequest { - private static final boolean DEFAULT_ALLOW_AUTOCREATEINDEX = true; - private final JSONObject persistent; - private final JSONObject data; - - public ClusterSettingsRequest() { - this(DEFAULT_ALLOW_AUTOCREATEINDEX); - } - public ClusterSettingsRequest(boolean autoCreateIndex) { - super("PUT","/_cluster/settings"); - this.data = new JSONObject(); - this.persistent = new JSONObject(); - this.data.put("persistent",this.persistent); - this.allowAutoCreateIndex(autoCreateIndex); - } + private static final boolean DEFAULT_ALLOW_AUTOCREATEINDEX = true; + private final JSONObject persistent; + private final JSONObject data; - public ClusterSettingsRequest allowAutoCreateIndex(boolean allow) { - this.persistent.put("action.auto_create_index", String.valueOf(allow)); - this.setQuery(this.data); - return this; - } + public ClusterSettingsRequest() { + this(DEFAULT_ALLOW_AUTOCREATEINDEX); + } + + public ClusterSettingsRequest(boolean autoCreateIndex) { + super("PUT", "/_cluster/settings"); + this.data = new JSONObject(); + this.persistent = new JSONObject(); + this.data.put("persistent", this.persistent); + this.allowAutoCreateIndex(autoCreateIndex); + } + + public ClusterSettingsRequest allowAutoCreateIndex(boolean allow) { + this.persistent.put("action.auto_create_index", String.valueOf(allow)); + this.setQuery(this.data); + return this; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CountRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CountRequest.java index 65c38471d..053be8cbc 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CountRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CountRequest.java @@ -21,12 +21,12 @@ */ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; -public class CountRequest extends BaseRequest{ +public class CountRequest extends BaseRequest { + + + public CountRequest(String alias, String dataType) { + super("GET", String.format("/%s/%s/_count", alias, dataType)); + } - - public CountRequest(String alias,String dataType) { - super("GET",String.format("/%s/%s/_count",alias,dataType)); - } - } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateAliasRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateAliasRequest.java index 1e46cc4de..f558fe45c 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateAliasRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateAliasRequest.java @@ -22,12 +22,12 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.put_alias.json -public class CreateAliasRequest extends BaseRequest{ +public class CreateAliasRequest extends BaseRequest { - public CreateAliasRequest(String index,String alias) { - super("PUT", String.format("/%s/_alias/%s",index,alias)); - } + public CreateAliasRequest(String index, String alias) { + super("PUT", String.format("/%s/_alias/%s", index, alias)); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateIndexRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateIndexRequest.java index 6f060196e..076032b29 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateIndexRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/CreateIndexRequest.java @@ -25,30 +25,31 @@ import org.json.JSONObject; //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.create.json //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.put_mapping.json -public class CreateIndexRequest extends BaseRequest{ +public class CreateIndexRequest extends BaseRequest { private JSONObject settings; private JSONObject mappings; public CreateIndexRequest(String index) { - super("PUT","/"+index); - this.mappings=new JSONObject(); + super("PUT", "/" + index); + this.mappings = new JSONObject(); } private void setRequest() { - JSONObject o=new JSONObject(); - if(this.mappings!=null) { + JSONObject o = new JSONObject(); + if (this.mappings != null) { o.put("mappings", this.mappings); } - if(this.settings!=null) { + if (this.settings != null) { o.put("settings", this.settings); } super.setQuery(o); } + @SuppressWarnings("hiding") public CreateIndexRequest mappings(JSONObject mappings) { - this.mappings=mappings; + this.mappings = mappings; this.setRequest(); return this; } @@ -59,11 +60,11 @@ public class CreateIndexRequest extends BaseRequest{ } public boolean hasMappings() { - return this.mappings!=null; + return this.mappings != null; } public boolean hasSettings() { - return this.settings!=null; + return this.settings != null; } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteAliasRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteAliasRequest.java index 92b481013..34da3a954 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteAliasRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteAliasRequest.java @@ -22,10 +22,10 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.delete_alias.json -public class DeleteAliasRequest extends BaseRequest{ +public class DeleteAliasRequest extends BaseRequest { - public DeleteAliasRequest(String index,String alias) { - super("DELETE","/"+index+"/_alias/"+alias); - } + public DeleteAliasRequest(String index, String alias) { + super("DELETE", "/" + index + "/_alias/" + alias); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteByQueryRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteByQueryRequest.java index 15c876e48..db884f643 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteByQueryRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteByQueryRequest.java @@ -23,22 +23,21 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder; -public class DeleteByQueryRequest extends BaseRequest { +public class DeleteByQueryRequest extends BaseRequest { - public DeleteByQueryRequest(String alias) { - this(alias, false); - } + public DeleteByQueryRequest(String alias) { + this(alias, false); + } - public DeleteByQueryRequest(String alias, boolean refresh) { - super("POST",String.format("/%s/_delete_by_query",alias), refresh); - } + public DeleteByQueryRequest(String alias, boolean refresh) { + super("POST", String.format("/%s/_delete_by_query", alias), refresh); + } - public DeleteByQueryRequest source(QueryBuilder query) { - this.setQuery(query); - return this; - } + public DeleteByQueryRequest source(QueryBuilder query) { + this.setQuery(query); + return this; + } - - -} \ No newline at end of file + +} diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteIndexRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteIndexRequest.java index f94f238b5..fb3c82adc 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteIndexRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteIndexRequest.java @@ -22,10 +22,10 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.delete.json -public class DeleteIndexRequest extends BaseRequest{ +public class DeleteIndexRequest extends BaseRequest { - public DeleteIndexRequest(String index) { - super("DELETE","/"+index); - } + public DeleteIndexRequest(String index) { + super("DELETE", "/" + index); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteRequest.java index 63202b169..a1a714765 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/DeleteRequest.java @@ -23,22 +23,25 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; public class DeleteRequest extends BaseRequest { - private final String alias; - private final String esId; - public DeleteRequest(String alias,String dataType,String esId) { - this(alias, dataType, esId, false); - } - public DeleteRequest(String alias,String dataType,String esId, boolean refresh) { - super("DELETE",String.format("/%s/%s/%s",alias,dataType,BaseRequest.urlEncodeValue(esId)), refresh); - this.alias = alias; - this.esId = esId; - } - protected String getAlias() { - return this.alias; - } + private final String alias; + private final String esId; - protected String getEsId() { - return this.esId; - } + public DeleteRequest(String alias, String dataType, String esId) { + this(alias, dataType, esId, false); + } + + public DeleteRequest(String alias, String dataType, String esId, boolean refresh) { + super("DELETE", String.format("/%s/%s/%s", alias, dataType, BaseRequest.urlEncodeValue(esId)), refresh); + this.alias = alias; + this.esId = esId; + } + + protected String getAlias() { + return this.alias; + } + + protected String getEsId() { + return this.esId; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetIndexRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetIndexRequest.java index bdcc4a9bf..59a06a5d2 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetIndexRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetIndexRequest.java @@ -24,10 +24,10 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.exists.json public class GetIndexRequest extends BaseRequest { - public GetIndexRequest(String index) { - super("HEAD","/"+index); - } + public GetIndexRequest(String index) { + super("HEAD", "/" + index); + } + - } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetInfoRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetInfoRequest.java index 2fa7a1699..fa27d2b52 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetInfoRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetInfoRequest.java @@ -24,10 +24,10 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; //https://github.com/elastic/elasticsearch/blob/6.4/rest-api-spec/src/main/resources/rest-api-spec/api/indices.exists.json public class GetInfoRequest extends BaseRequest { - public GetInfoRequest() { - super("GET","/"); - } + public GetInfoRequest() { + super("GET", "/"); + } + - } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetRequest.java index a589b207b..6092d88b0 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/GetRequest.java @@ -23,11 +23,11 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; import javax.annotation.Nonnull; -public class GetRequest extends BaseRequest{ +public class GetRequest extends BaseRequest { - public GetRequest(String alias,String dataType,@Nonnull String esId) { - super("GET",String.format("/%s/%s/%s",alias,dataType,BaseRequest.urlEncodeValue(esId))); - } + public GetRequest(String alias, String dataType, @Nonnull String esId) { + super("GET", String.format("/%s/%s/%s", alias, dataType, BaseRequest.urlEncodeValue(esId))); + } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/IndexRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/IndexRequest.java index a3ee578a9..81e218ec9 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/IndexRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/IndexRequest.java @@ -25,37 +25,37 @@ import javax.annotation.Nullable; public class IndexRequest extends BaseRequest { - private final String alias; - private final String esId; - - public IndexRequest(String alias, String dataType) { - this(alias, dataType, null); - } - - public IndexRequest(String alias, String dataType, @Nullable String esId) { - super("POST", esId != null ? String.format("/%s/%s/%s", alias, dataType, BaseRequest.urlEncodeValue(esId)) - : String.format("/%s/%s", alias, dataType)); - this.alias = alias; - this.esId = esId; - } - - public IndexRequest(String alias, String dataType, @Nullable String esId, boolean refresh) { - super("POST", esId != null ? String.format("/%s/%s/%s", alias, dataType, BaseRequest.urlEncodeValue(esId)) - : String.format("/%s/%s", alias, dataType),refresh); - this.alias = alias; - this.esId = esId; - } - - public void source(String content) { - super.setQuery(content); - } - - protected String getAlias() { - return this.alias; - } - - protected String getEsId() { - return this.esId; - } + private final String alias; + private final String esId; + + public IndexRequest(String alias, String dataType) { + this(alias, dataType, null); + } + + public IndexRequest(String alias, String dataType, @Nullable String esId) { + super("POST", esId != null ? String.format("/%s/%s/%s", alias, dataType, BaseRequest.urlEncodeValue(esId)) + : String.format("/%s/%s", alias, dataType)); + this.alias = alias; + this.esId = esId; + } + + public IndexRequest(String alias, String dataType, @Nullable String esId, boolean refresh) { + super("POST", esId != null ? String.format("/%s/%s/%s", alias, dataType, BaseRequest.urlEncodeValue(esId)) + : String.format("/%s/%s", alias, dataType), refresh); + this.alias = alias; + this.esId = esId; + } + + public void source(String content) { + super.setQuery(content); + } + + protected String getAlias() { + return this.alias; + } + + protected String getEsId() { + return this.esId; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListAliasesRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListAliasesRequest.java index 6ea945f78..d77910917 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListAliasesRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListAliasesRequest.java @@ -21,11 +21,11 @@ */ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; -public class ListAliasesRequest extends BaseRequest{ +public class ListAliasesRequest extends BaseRequest { - - public ListAliasesRequest() { - super("GET","/_cat/aliases"); - } + + public ListAliasesRequest() { + super("GET", "/_cat/aliases"); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListIndicesRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListIndicesRequest.java index e65de56db..8a060fd43 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListIndicesRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/ListIndicesRequest.java @@ -21,11 +21,11 @@ */ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; -public class ListIndicesRequest extends BaseRequest{ +public class ListIndicesRequest extends BaseRequest { - - public ListIndicesRequest() { - super("GET","/_cat/indices"); - } + + public ListIndicesRequest() { + super("GET", "/_cat/indices"); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/NodeStatsRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/NodeStatsRequest.java index dfb9b2cfc..022563a36 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/NodeStatsRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/NodeStatsRequest.java @@ -21,10 +21,10 @@ */ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; -public class NodeStatsRequest extends BaseRequest{ +public class NodeStatsRequest extends BaseRequest { - - public NodeStatsRequest() { - super("GET","/_nodes/stats"); - } + + public NodeStatsRequest() { + super("GET", "/_nodes/stats"); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/RefreshIndexRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/RefreshIndexRequest.java index 37760b697..327f81f50 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/RefreshIndexRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/RefreshIndexRequest.java @@ -21,11 +21,11 @@ */ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; -public class RefreshIndexRequest extends BaseRequest{ +public class RefreshIndexRequest extends BaseRequest { - public RefreshIndexRequest(String alias) { - super("GET",String.format("/%s/_refresh",alias)); - } + public RefreshIndexRequest(String alias) { + super("GET", String.format("/%s/_refresh", alias)); + } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/SearchRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/SearchRequest.java index bd6559371..113cb4e1e 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/SearchRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/SearchRequest.java @@ -23,15 +23,15 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.requests; import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilder; -public class SearchRequest extends BaseRequest{ +public class SearchRequest extends BaseRequest { - public SearchRequest(String alias,String dataType) { - super("POST",String.format("/%s/%s/_search", alias,dataType)); - } + public SearchRequest(String alias, String dataType) { + super("POST", String.format("/%s/%s/_search", alias, dataType)); + } - @Override - public void setQuery(QueryBuilder query){ - super.setQuery(query); - } + @Override + public void setQuery(QueryBuilder query) { + super.setQuery(query); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateByQueryRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateByQueryRequest.java index 8bca04ff6..d351352af 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateByQueryRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateByQueryRequest.java @@ -28,89 +28,89 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.queries.QueryBuilders; public class UpdateByQueryRequest extends BaseRequest { - private JSONObject params; - private final String alias; - - public UpdateByQueryRequest(String alias, String dataType) { - this(alias, dataType, false); - } + private JSONObject params; + private final String alias; - public UpdateByQueryRequest(String alias, String dataType, boolean refresh) { - super("POST", String.format("/%s/%s/_update_by_query", alias, dataType), refresh); - this.alias = alias; - this.params = null; - } + public UpdateByQueryRequest(String alias, String dataType) { + this(alias, dataType, false); + } - public void source(String esId, JSONObject map) { - this.source(map, QueryBuilders.matchQuery("_id", esId)); - } + public UpdateByQueryRequest(String alias, String dataType, boolean refresh) { + super("POST", String.format("/%s/%s/_update_by_query", alias, dataType), refresh); + this.alias = alias; + this.params = null; + } - public void source(JSONObject map, QueryBuilder query) { - JSONObject outer = new JSONObject(); - outer.put("query", query.getInner()); - JSONObject script = new JSONObject(); - script.put("lang", "painless"); - script.put("inline", this.createInline(map)); - if(this.params!=null) { - script.put("params",this.params); - } - outer.put("script", script); - super.setQuery(outer.toString()); - } + public void source(String esId, JSONObject map) { + this.source(map, QueryBuilders.matchQuery("_id", esId)); + } - private String createInline(JSONObject map) { - String s = "", k, pkey; - int i = 1; - Object value; - for (Object key : map.keySet()) { - k = String.valueOf(key); - value = map.get(k); - if (value instanceof JSONObject || value instanceof JSONArray) { - pkey = String.format("p%d", i++); - if (value instanceof JSONObject) { - this.withParam(pkey, (JSONObject) value); - } else { - this.withParam(pkey, (JSONArray) value); - } + public void source(JSONObject map, QueryBuilder query) { + JSONObject outer = new JSONObject(); + outer.put("query", query.getInner()); + JSONObject script = new JSONObject(); + script.put("lang", "painless"); + script.put("inline", this.createInline(map)); + if (this.params != null) { + script.put("params", this.params); + } + outer.put("script", script); + super.setQuery(outer.toString()); + } - s += String.format("ctx._source['%s']=%s;", key, "params." + pkey); - } else { - s += String.format("ctx._source['%s']=%s;", key, escpaped(value)); - } - } - return s; - } + private String createInline(JSONObject map) { + String s = "", k, pkey; + int i = 1; + Object value; + for (Object key : map.keySet()) { + k = String.valueOf(key); + value = map.get(k); + if (value instanceof JSONObject || value instanceof JSONArray) { + pkey = String.format("p%d", i++); + if (value instanceof JSONObject) { + this.withParam(pkey, (JSONObject) value); + } else { + this.withParam(pkey, (JSONArray) value); + } - private UpdateByQueryRequest withParam(String key, JSONArray p) { - if (this.params == null) { - this.params = new JSONObject(); - } - this.params.put(key, p); - return this; - } + s += String.format("ctx._source['%s']=%s;", key, "params." + pkey); + } else { + s += String.format("ctx._source['%s']=%s;", key, escpaped(value)); + } + } + return s; + } - private UpdateByQueryRequest withParam(String key, JSONObject p) { - if (this.params == null) { - this.params = new JSONObject(); - } - this.params.put(key, p); - return this; - } + private UpdateByQueryRequest withParam(String key, JSONArray p) { + if (this.params == null) { + this.params = new JSONObject(); + } + this.params.put(key, p); + return this; + } - private String escpaped(Object value) { - String s = ""; - if (value instanceof Boolean || value instanceof Integer || value instanceof Long || value instanceof Float - || value instanceof Double) { - s = String.valueOf(value); - } else { - s = "\"" + String.valueOf(value) + "\""; - } - return s; + private UpdateByQueryRequest withParam(String key, JSONObject p) { + if (this.params == null) { + this.params = new JSONObject(); + } + this.params.put(key, p); + return this; + } - } + private String escpaped(Object value) { + String s = ""; + if (value instanceof Boolean || value instanceof Integer || value instanceof Long || value instanceof Float + || value instanceof Double) { + s = String.valueOf(value); + } else { + s = "\"" + String.valueOf(value) + "\""; + } + return s; - protected String getAlias() { - return this.alias; - } + } + + protected String getAlias() { + return this.alias; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateRequest.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateRequest.java index 16923b238..eca3b4b1d 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateRequest.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/requests/UpdateRequest.java @@ -31,123 +31,125 @@ import org.slf4j.LoggerFactory; public class UpdateRequest extends BaseRequest { - private static final Logger LOG = LoggerFactory.getLogger(UpdateRequest.class); - private JSONObject params; - private String alias; - private String esId; - private int retries; - - public UpdateRequest(String alias, String dataType, String esId) { - this(alias, dataType, esId, BaseRequest.DEFAULT_RETRIES); - } - public UpdateRequest(String alias, String dataType, String esId, boolean refresh) { - this(alias, dataType, esId, BaseRequest.DEFAULT_RETRIES, refresh); - } - public UpdateRequest(String alias, String dataType, String esId, int retries) { - this(alias, dataType, esId, retries, false); - } - - public UpdateRequest(String alias, String dataType, String esId, int retries, boolean refresh) { - this(String.format("/%s/%s/%s/_update", alias, dataType, BaseRequest.urlEncodeValue(esId)), refresh); - this.alias = alias; - this.esId = esId; - this.retries = retries; - } - - public UpdateRequest(String uri, boolean refresh) { - super("POST", uri, refresh, BaseRequest.DEFAULT_RETRIES); - this.params = null; - this.retries = 1; - - } - - - - private UpdateRequest withParam(String key, JSONObject p) { - if (this.params == null) { - this.params = new JSONObject(); - } - this.params.put(key, p); - return this; - } - - private UpdateRequest withParam(String key, JSONArray p) { - if (this.params == null) { - this.params = new JSONObject(); - } - this.params.put(key, p); - return this; - } - - public void source(JSONObject map) { - this.source(map, null); - } - - public void source(JSONObject map, List onlyForInsert) { - JSONObject outer = new JSONObject(); - JSONObject script = new JSONObject(); - script.put("lang", "painless"); - script.put("source", this.createInline(map, onlyForInsert)); - if (this.params != null) { - script.put("params", this.params); - } - outer.put("script", script); - outer.put("upsert", map); - LOG.debug("update payload: " + outer.toString()); - super.setQuery(outer.toString()); - } - - private String createInline(JSONObject map, List onlyForInsert) { - if (onlyForInsert == null) { - onlyForInsert = new ArrayList(); - } - String s = "", k = ""; - Object value; - String pkey; - int i = 0; - for (Object key : map.keySet()) { - k = String.valueOf(key); - if (onlyForInsert.contains(k)) { - continue; - } - value = map.get(k); - if (value instanceof JSONObject || value instanceof JSONArray) { - pkey = String.format("p%d", i++); - if (value instanceof JSONObject) { - this.withParam(pkey, (JSONObject) value); - } else { - this.withParam(pkey, (JSONArray) value); - } - - s += String.format("ctx._source['%s']=%s;", key, "params." + pkey); - } else { - s += String.format("ctx._source['%s']=%s;", key, escpaped(value)); - } - } - return s; - } - - private String escpaped(Object value) { - String s = ""; - if (value instanceof Boolean || value instanceof Integer || value instanceof Long || value instanceof Float - || value instanceof Double) { - s = String.valueOf(value); - } else { - s = "\"" + String.valueOf(value) + "\""; - } - return s; - - } - - protected String getAlias() { - return this.alias; - } - - protected String getEsId() { - return this.esId; - } - - protected int getRetries() { - return this.retries; - } + private static final Logger LOG = LoggerFactory.getLogger(UpdateRequest.class); + private JSONObject params; + private String alias; + private String esId; + private int retries; + + public UpdateRequest(String alias, String dataType, String esId) { + this(alias, dataType, esId, BaseRequest.DEFAULT_RETRIES); + } + + public UpdateRequest(String alias, String dataType, String esId, boolean refresh) { + this(alias, dataType, esId, BaseRequest.DEFAULT_RETRIES, refresh); + } + + public UpdateRequest(String alias, String dataType, String esId, int retries) { + this(alias, dataType, esId, retries, false); + } + + public UpdateRequest(String alias, String dataType, String esId, int retries, boolean refresh) { + this(String.format("/%s/%s/%s/_update", alias, dataType, BaseRequest.urlEncodeValue(esId)), refresh); + this.alias = alias; + this.esId = esId; + this.retries = retries; + } + + public UpdateRequest(String uri, boolean refresh) { + super("POST", uri, refresh, BaseRequest.DEFAULT_RETRIES); + this.params = null; + this.retries = 1; + + } + + + + private UpdateRequest withParam(String key, JSONObject p) { + if (this.params == null) { + this.params = new JSONObject(); + } + this.params.put(key, p); + return this; + } + + private UpdateRequest withParam(String key, JSONArray p) { + if (this.params == null) { + this.params = new JSONObject(); + } + this.params.put(key, p); + return this; + } + + public void source(JSONObject map) { + this.source(map, null); + } + + public void source(JSONObject map, List onlyForInsert) { + JSONObject outer = new JSONObject(); + JSONObject script = new JSONObject(); + script.put("lang", "painless"); + script.put("source", this.createInline(map, onlyForInsert)); + if (this.params != null) { + script.put("params", this.params); + } + outer.put("script", script); + outer.put("upsert", map); + LOG.debug("update payload: " + outer.toString()); + super.setQuery(outer.toString()); + } + + private String createInline(JSONObject map, List onlyForInsert) { + if (onlyForInsert == null) { + onlyForInsert = new ArrayList(); + } + String s = "", k = ""; + Object value; + String pkey; + int i = 0; + for (Object key : map.keySet()) { + k = String.valueOf(key); + if (onlyForInsert.contains(k)) { + continue; + } + value = map.get(k); + if (value instanceof JSONObject || value instanceof JSONArray) { + pkey = String.format("p%d", i++); + if (value instanceof JSONObject) { + this.withParam(pkey, (JSONObject) value); + } else { + this.withParam(pkey, (JSONArray) value); + } + + s += String.format("ctx._source['%s']=%s;", key, "params." + pkey); + } else { + s += String.format("ctx._source['%s']=%s;", key, escpaped(value)); + } + } + return s; + } + + private String escpaped(Object value) { + String s = ""; + if (value instanceof Boolean || value instanceof Integer || value instanceof Long || value instanceof Float + || value instanceof Double) { + s = String.valueOf(value); + } else { + s = "\"" + String.valueOf(value) + "\""; + } + return s; + + } + + protected String getAlias() { + return this.alias; + } + + protected String getEsId() { + return this.esId; + } + + protected int getRetries() { + return this.retries; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AcknowledgedResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AcknowledgedResponse.java index c022c4e6f..1d178a103 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AcknowledgedResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AcknowledgedResponse.java @@ -24,19 +24,19 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.responses; import org.elasticsearch.client.Response; import org.json.JSONObject; -public class AcknowledgedResponse extends BaseResponse{ +public class AcknowledgedResponse extends BaseResponse { - private boolean isAcknowledged; + private boolean isAcknowledged; - public AcknowledgedResponse(Response response) { - super(response); - JSONObject o = this.getJson(response); - if(o!=null) { - this.isAcknowledged=o.getBoolean("acknowledged"); - } - } + public AcknowledgedResponse(Response response) { + super(response); + JSONObject o = this.getJson(response); + if (o != null) { + this.isAcknowledged = o.getBoolean("acknowledged"); + } + } - public boolean isAcknowledged() { - return this.isAcknowledged; - } + public boolean isAcknowledged() { + return this.isAcknowledged; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AggregationEntries.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AggregationEntries.java index 4a0564cd9..752c15e37 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AggregationEntries.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/AggregationEntries.java @@ -25,24 +25,25 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -public class AggregationEntries extends LinkedHashMap{ +public class AggregationEntries extends LinkedHashMap { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Return page with keys - * @param size elements - * @param offset start position in list. - * @return List with selected values - */ - public String[] getKeysAsPagedStringList(long size, long offset) { - List ltps = new ArrayList(); - String[] keys = keySet().toArray(new String[0]); - for (long i = offset; i < keys.length && i < offset + size; i++) { - ltps.add(keys[(int) i]); - } - return ltps.toArray(new String[0]); - } + /** + * Return page with keys + * + * @param size elements + * @param offset start position in list. + * @return List with selected values + */ + public String[] getKeysAsPagedStringList(long size, long offset) { + List ltps = new ArrayList(); + String[] keys = keySet().toArray(new String[0]); + for (long i = offset; i < keys.length && i < offset + size; i++) { + ltps.add(keys[(int) i]); + } + return ltps.toArray(new String[0]); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/BaseResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/BaseResponse.java index a3a1b16e1..2746be4a4 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/BaseResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/BaseResponse.java @@ -32,66 +32,67 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BaseResponse { - private static final Logger LOG = LoggerFactory.getLogger(BaseResponse.class); + private static final Logger LOG = LoggerFactory.getLogger(BaseResponse.class); - private final int responseCode; + private final int responseCode; - BaseResponse(Response response) { - this.responseCode = response != null ? response.getStatusLine().getStatusCode() : 0; - } + BaseResponse(Response response) { + this.responseCode = response != null ? response.getStatusLine().getStatusCode() : 0; + } - int getResponseCode() { - return this.responseCode; - } + int getResponseCode() { + return this.responseCode; + } - public boolean isResponseSucceeded() { - return this.responseCode < 300; - } + public boolean isResponseSucceeded() { + return this.responseCode < 300; + } - JSONObject getJson(Response response) { - if(response==null) { - LOG.warn("unable to parse response. response is null."); - return null; - } - try { - String sresponse = EntityUtils.toString(response.getEntity()); - LOG.debug("parsing response={}", sresponse); - return new JSONObject(sresponse); - } catch (UnsupportedOperationException | IOException e) { - LOG.warn("error parsing es response: {}", e.getMessage()); - return null; - } + JSONObject getJson(Response response) { + if (response == null) { + LOG.warn("unable to parse response. response is null."); + return null; + } + try { + String sresponse = EntityUtils.toString(response.getEntity()); + LOG.debug("parsing response={}", sresponse); + return new JSONObject(sresponse); + } catch (UnsupportedOperationException | IOException e) { + LOG.warn("error parsing es response: {}", e.getMessage()); + return null; + } - } + } - JSONObject getJson(String json) { - return new JSONObject(json); - } + JSONObject getJson(String json) { + return new JSONObject(json); + } - /** - * @param response - * @return - */ - List getLines(Response response){ - return this.getLines(response,true); - } - List getLines(Response response,boolean ignoreEmpty) { - try { - String sresponse = EntityUtils.toString(response.getEntity()); - LOG.debug("parsing response={}", sresponse); - String[] hlp = sresponse.split("\n"); - List lines=new ArrayList(); - for(String h:hlp) { - if(ignoreEmpty && h.trim().length()==0) { - continue; - } - lines.add(h); - } - return lines; - } catch (UnsupportedOperationException | IOException e) { - LOG.warn("error parsing es response: {}", e.getMessage()); - return null; - } + /** + * @param response + * @return + */ + List getLines(Response response) { + return this.getLines(response, true); + } - } + List getLines(Response response, boolean ignoreEmpty) { + try { + String sresponse = EntityUtils.toString(response.getEntity()); + LOG.debug("parsing response={}", sresponse); + String[] hlp = sresponse.split("\n"); + List lines = new ArrayList(); + for (String h : hlp) { + if (ignoreEmpty && h.trim().length() == 0) { + continue; + } + lines.add(h); + } + return lines; + } catch (UnsupportedOperationException | IOException e) { + LOG.warn("error parsing es response: {}", e.getMessage()); + return null; + } + + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterHealthResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterHealthResponse.java index cb365d2b3..27abbea8a 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterHealthResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterHealthResponse.java @@ -56,6 +56,7 @@ public class ClusterHealthResponse extends BaseResponse { public boolean isTimedOut() { return this.timedOut; } + @SuppressWarnings("hiding") public boolean isStatusMinimal(String status) { if (status == null) { diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterSettingsResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterSettingsResponse.java index 49d9f864a..ee38bbf00 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterSettingsResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ClusterSettingsResponse.java @@ -25,7 +25,7 @@ import org.elasticsearch.client.Response; public class ClusterSettingsResponse extends AcknowledgedResponse { - public ClusterSettingsResponse(Response response) { + public ClusterSettingsResponse(Response response) { super(response); } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateAliasResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateAliasResponse.java index 1e792063e..2194e84b8 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateAliasResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateAliasResponse.java @@ -25,8 +25,8 @@ import org.elasticsearch.client.Response; public class CreateAliasResponse extends AcknowledgedResponse { - public CreateAliasResponse(Response response) { - super(response); - } + public CreateAliasResponse(Response response) { + super(response); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateIndexResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateIndexResponse.java index 13ac8d5bf..af77d5526 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateIndexResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/CreateIndexResponse.java @@ -25,8 +25,8 @@ import org.elasticsearch.client.Response; public class CreateIndexResponse extends AcknowledgedResponse { - public CreateIndexResponse(Response response) { - super(response); - } + public CreateIndexResponse(Response response) { + super(response); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteAliasResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteAliasResponse.java index 53756af02..584cb9d9b 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteAliasResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteAliasResponse.java @@ -25,8 +25,8 @@ import org.elasticsearch.client.Response; public class DeleteAliasResponse extends AcknowledgedResponse { - public DeleteAliasResponse(Response response) { - super(response); - } + public DeleteAliasResponse(Response response) { + super(response); + } -} \ No newline at end of file +} diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteByQueryResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteByQueryResponse.java index 7c0b1352a..94c86dd58 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteByQueryResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteByQueryResponse.java @@ -26,29 +26,29 @@ import org.json.JSONObject; /** * {"took":1,"batches":0,"retries":{"search":0,"bulk":0},"throttled_millis":0,"total":0,"deleted":0,"noops":0,"requests_per_second":-1,"failures":[],"version_conflicts":0,"throttled_until_millis":0,"timed_out":false} + * * @author jack * */ public class DeleteByQueryResponse extends BaseResponse { - private int deleted; + private int deleted; - public DeleteByQueryResponse(Response response) { - super(response); - try { - JSONObject o = this.getJson(response); - if (o != null) { - this.deleted = o.getInt("deleted"); - } - } - catch(Exception e) { - this.deleted=0; - } + public DeleteByQueryResponse(Response response) { + super(response); + try { + JSONObject o = this.getJson(response); + if (o != null) { + this.deleted = o.getInt("deleted"); + } + } catch (Exception e) { + this.deleted = 0; + } - } + } - public int getDeleted() { - return this.deleted; - } + public int getDeleted() { + return this.deleted; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteIndexResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteIndexResponse.java index a0e589033..94fcbc5fa 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteIndexResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteIndexResponse.java @@ -25,8 +25,8 @@ import org.elasticsearch.client.Response; public class DeleteIndexResponse extends AcknowledgedResponse { - public DeleteIndexResponse(Response response) { - super(response); - } + public DeleteIndexResponse(Response response) { + super(response); + } -} \ No newline at end of file +} diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteResponse.java index d4dee0441..f6202d009 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/DeleteResponse.java @@ -26,28 +26,26 @@ import org.json.JSONObject; public class DeleteResponse extends BaseResponse { - private boolean isDeleted; - - public DeleteResponse(Response response) { - super(response); - if (this.isResponseSucceeded()) { - - JSONObject o = this.getJson(response); - if (o != null) { - this.isDeleted = "deleted".equals(o.getString("result")); - } - else { - this.isDeleted=false; - } - } - else { - this.isDeleted=false; - } - - } - - public boolean isDeleted() { - return this.isDeleted; - } + private boolean isDeleted; + + public DeleteResponse(Response response) { + super(response); + if (this.isResponseSucceeded()) { + + JSONObject o = this.getJson(response); + if (o != null) { + this.isDeleted = "deleted".equals(o.getString("result")); + } else { + this.isDeleted = false; + } + } else { + this.isDeleted = false; + } + + } + + public boolean isDeleted() { + return this.isDeleted; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetInfoResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetInfoResponse.java index 1bc43a6d0..946a8fb4a 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetInfoResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetInfoResponse.java @@ -28,49 +28,40 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.data.EsVersion; public class GetInfoResponse extends BaseResponse { /** - * { - * "name" : "kpOdXt-", - * "cluster_name" : "docker-cluster", - * "cluster_uuid" : "qags6CGGTrS75iBhrAdsgg", - * "version" : { - * "number" : "6.4.3", - * "build_flavor" : "default", - * "build_type" : "tar", - * "build_hash" : "fe40335", - * "build_date" : "2018-10-30T23:17:19.084789Z", - * "build_snapshot" : false, - * "lucene_version" : "7.4.0", - * "minimum_wire_compatibility_version" : "5.6.0", - * "minimum_index_compatibility_version" : "5.0.0" - * }, - * "tagline" : "You Know, for Search" - *} + * { "name" : "kpOdXt-", "cluster_name" : "docker-cluster", "cluster_uuid" : "qags6CGGTrS75iBhrAdsgg", "version" : { + * "number" : "6.4.3", "build_flavor" : "default", "build_type" : "tar", "build_hash" : "fe40335", "build_date" : + * "2018-10-30T23:17:19.084789Z", "build_snapshot" : false, "lucene_version" : "7.4.0", + * "minimum_wire_compatibility_version" : "5.6.0", "minimum_index_compatibility_version" : "5.0.0" }, "tagline" : + * "You Know, for Search" } */ - private final String clusterName; - private final String name; - - private final EsVersion version; - public GetInfoResponse(Response response) throws Exception { + private final String clusterName; + private final String name; + + private final EsVersion version; + + public GetInfoResponse(Response response) throws Exception { super(response); JSONObject o = this.getJson(response); - if(o==null) { - throw new Exception("unable to read response"); + if (o == null) { + throw new Exception("unable to read response"); } this.name = o.getString("name"); this.clusterName = o.getString("cluster_name"); this.version = new EsVersion(o.getJSONObject("version").getString("number")); } - public String getClusterName() { - return clusterName; - } - public String getName() { - return name; - } - public EsVersion getVersion() { - return version; - } - - - + public String getClusterName() { + return clusterName; + } + + public String getName() { + return name; + } + + public EsVersion getVersion() { + return version; + } + + + } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetResponse.java index 0c9b511e4..47ab7e859 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/GetResponse.java @@ -27,28 +27,28 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; public class GetResponse extends BaseResponse { - private boolean found; - private SearchHit result; - - public GetResponse(Response response) { - super(response); - if (this.isResponseSucceeded()) { - JSONObject o = this.getJson(response); - this.found = o.getBoolean("found"); - this.result = new SearchHit(o); - } else { - this.found = false; - this.result = null; - } - - } - - public boolean isExists() { - return this.found; - } - - public String getSourceAsBytesRef() { - return this.result.getSourceAsString(); - } + private boolean found; + private SearchHit result; + + public GetResponse(Response response) { + super(response); + if (this.isResponseSucceeded()) { + JSONObject o = this.getJson(response); + this.found = o.getBoolean("found"); + this.result = new SearchHit(o); + } else { + this.found = false; + this.result = null; + } + + } + + public boolean isExists() { + return this.found; + } + + public String getSourceAsBytesRef() { + return this.result.getSourceAsString(); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/IndexResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/IndexResponse.java index fc2faf99d..9978cfde3 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/IndexResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/IndexResponse.java @@ -24,30 +24,31 @@ package org.onap.ccsdk.features.sdnr.wt.common.database.responses; import org.elasticsearch.client.Response; import org.json.JSONObject; -public class IndexResponse extends BaseResponse{ - - private boolean isCreated; - private String id; - private boolean isUpdated; - - public IndexResponse(Response response) { - super(response); - JSONObject o = this.getJson(response); - this.id=o.getString("_id"); - this.isCreated="created".equals(o.getString("result")); - this.isUpdated="updated".equals(o.getString("result")); - //{"_index":"historicalperformance24h","_type":"historicalperformance24h","_id":"CbZxvWwB4xjGPydc9ida","_version":1,"result":"created","_shards":{"total":4,"successful":1,"failed":0},"_seq_no":1,"_primary_term":1} - } - - public String getId() { - return this.id; - } - - public boolean isCreated() { - return this.isCreated; - } - public boolean isUpdated() { - return this.isUpdated; - } +public class IndexResponse extends BaseResponse { + + private boolean isCreated; + private String id; + private boolean isUpdated; + + public IndexResponse(Response response) { + super(response); + JSONObject o = this.getJson(response); + this.id = o.getString("_id"); + this.isCreated = "created".equals(o.getString("result")); + this.isUpdated = "updated".equals(o.getString("result")); + //{"_index":"historicalperformance24h","_type":"historicalperformance24h","_id":"CbZxvWwB4xjGPydc9ida","_version":1,"result":"created","_shards":{"total":4,"successful":1,"failed":0},"_seq_no":1,"_primary_term":1} + } + + public String getId() { + return this.id; + } + + public boolean isCreated() { + return this.isCreated; + } + + public boolean isUpdated() { + return this.isUpdated; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListAliasesResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListAliasesResponse.java index b5b073f3b..7956b2bfc 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListAliasesResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListAliasesResponse.java @@ -43,25 +43,27 @@ public class ListAliasesResponse extends BaseResponse { * faultcurrent faultcurrent-v1 - - - * connectionlog connectionlog-v1 - - - */ - private final AliasesEntryList entries; + private final AliasesEntryList entries; + public ListAliasesResponse(Response response) throws ParseException { super(response); - List lines=this.getLines(response); + List lines = this.getLines(response); this.entries = new AliasesEntryList(); - if(lines!=null) { - for(String line:lines) { - this.entries.add(new AliasesEntry(line)); - } + if (lines != null) { + for (String line : lines) { + this.entries.add(new AliasesEntry(line)); + } } } + /** * * @return null if parsing failed otherwise valid (=>no entries may also be valid) */ - public AliasesEntryList getEntries(){ - return this.entries; + public AliasesEntryList getEntries() { + return this.entries; } - - + + } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListIndicesResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListIndicesResponse.java index 461ae7a33..f6e854abd 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListIndicesResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/ListIndicesResponse.java @@ -42,26 +42,27 @@ public class ListIndicesResponse extends BaseResponse { * yellow open networkelement-connection-v1 YT3lj0AKRoOmtN30Zbdfqw 5 1 0 0 1.2kb 1.2kb * yellow open connectionlog-v1 7yrVaaM1QjyO5eMsCUHNHQ 5 1 0 0 1.2kb 1.2kb */ - private final IndicesEntryList entries; - public ListIndicesResponse(Response response) throws ParseException { + private final IndicesEntryList entries; + + public ListIndicesResponse(Response response) throws ParseException { super(response); - List lines=this.getLines(response); + List lines = this.getLines(response); this.entries = new IndicesEntryList(); - if(lines!=null) { - for(String line:lines) { - this.entries.add(new IndicesEntry(line)); - } + if (lines != null) { + for (String line : lines) { + this.entries.add(new IndicesEntry(line)); + } } - + } - /** - * @return - */ - public IndicesEntryList getEntries() { - return this.entries; - } - - - + /** + * @return + */ + public IndicesEntryList getEntries() { + return this.entries; + } + + + } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/NodeStatsResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/NodeStatsResponse.java index 1d308d127..ba5a83784 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/NodeStatsResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/NodeStatsResponse.java @@ -31,83 +31,86 @@ import org.json.JSONObject; public class NodeStatsResponse extends BaseResponse { - private NodesInfo nodesInfo; - private Map nodeStats; - - public NodesInfo getNodesInfo() { - return this.nodesInfo; - } - public Map getNodeStatistics(){ - return this.nodeStats; - } - public NodeStatsResponse(Response response) throws UnsupportedOperationException, IOException, JSONException { - super(response); - - JSONObject o = this.getJson(response); - String k; - if (o != null) { - this.nodesInfo = new NodesInfo(o.getJSONObject("_nodes")); - this.nodeStats = new HashMap<>(); - if(this.nodesInfo.successful>0) { - JSONObject stats = o.getJSONObject("nodes"); - for (Object key : stats.keySet()) { - k=String.valueOf(key); - this.nodeStats.put(k, new NodeStats(k,stats.getJSONObject(k))); - } - } - } - } - - - - public static class NodesInfo{ - @Override - public String toString() { - return "NodesInfo [total=" + total + ", successful=" + successful + ", failed=" + failed + "]"; - } - - public final int total; - public final int successful; - public final int failed; - - public NodesInfo(JSONObject o) { - this.total =o.getInt("total"); - this.successful = o.getInt("successful"); - this.failed = o.getInt("failed"); - } - } - public static class NodeStats{ - public final String name; - public final NodeTotalDiskStats total; - - @Override - public String toString() { - return "NodeStats [name=" + name + ", total=" + total + "]"; - } - - public NodeStats(String name,JSONObject o) { - this.name = name; - this.total = new NodeTotalDiskStats(o.getJSONObject("fs").getJSONObject("total")); - } - } - public static class NodeTotalDiskStats{ - public final long total; - public final long available; - public final long free; - - @Override - public String toString() { - return "NodeTotalDiskStats [total=" + total + ", available=" + available + ", free=" + free - + ", getUseDiskPercentage()=" + getUseDiskPercentage() + "]"; - } - - public float getUseDiskPercentage() { - return (total-available)*100.0f/(float)total; - } - public NodeTotalDiskStats(JSONObject o) { - this.total = o.getLong("total_in_bytes"); - this.available = o.getLong("available_in_bytes"); - this.free = o.getLong("free_in_bytes"); - } - } + private NodesInfo nodesInfo; + private Map nodeStats; + + public NodesInfo getNodesInfo() { + return this.nodesInfo; + } + + public Map getNodeStatistics() { + return this.nodeStats; + } + + public NodeStatsResponse(Response response) throws UnsupportedOperationException, IOException, JSONException { + super(response); + + JSONObject o = this.getJson(response); + String k; + if (o != null) { + this.nodesInfo = new NodesInfo(o.getJSONObject("_nodes")); + this.nodeStats = new HashMap<>(); + if (this.nodesInfo.successful > 0) { + JSONObject stats = o.getJSONObject("nodes"); + for (Object key : stats.keySet()) { + k = String.valueOf(key); + this.nodeStats.put(k, new NodeStats(k, stats.getJSONObject(k))); + } + } + } + } + + + + public static class NodesInfo { + @Override + public String toString() { + return "NodesInfo [total=" + total + ", successful=" + successful + ", failed=" + failed + "]"; + } + + public final int total; + public final int successful; + public final int failed; + + public NodesInfo(JSONObject o) { + this.total = o.getInt("total"); + this.successful = o.getInt("successful"); + this.failed = o.getInt("failed"); + } + } + public static class NodeStats { + public final String name; + public final NodeTotalDiskStats total; + + @Override + public String toString() { + return "NodeStats [name=" + name + ", total=" + total + "]"; + } + + public NodeStats(String name, JSONObject o) { + this.name = name; + this.total = new NodeTotalDiskStats(o.getJSONObject("fs").getJSONObject("total")); + } + } + public static class NodeTotalDiskStats { + public final long total; + public final long available; + public final long free; + + @Override + public String toString() { + return "NodeTotalDiskStats [total=" + total + ", available=" + available + ", free=" + free + + ", getUseDiskPercentage()=" + getUseDiskPercentage() + "]"; + } + + public float getUseDiskPercentage() { + return (total - available) * 100.0f / (float) total; + } + + public NodeTotalDiskStats(JSONObject o) { + this.total = o.getLong("total_in_bytes"); + this.available = o.getLong("available_in_bytes"); + this.free = o.getLong("free_in_bytes"); + } + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/RefreshIndexResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/RefreshIndexResponse.java index eb56c7171..f55ff1a66 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/RefreshIndexResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/RefreshIndexResponse.java @@ -32,17 +32,17 @@ import org.json.JSONObject; */ public class RefreshIndexResponse extends BaseResponse { - private boolean succeeded; + private boolean succeeded; - public RefreshIndexResponse(Response response) { - super(response); - JSONObject o = this.getJson(response); - this.succeeded = o.getJSONObject("_shards").getInt("failed") == 0; - // {"_index":"historicalperformance24h","_type":"historicalperformance24h","_id":"CbZxvWwB4xjGPydc9ida","_version":1,"result":"created","_shards":{"total":4,"successful":1,"failed":0},"_seq_no":1,"_primary_term":1} - } + public RefreshIndexResponse(Response response) { + super(response); + JSONObject o = this.getJson(response); + this.succeeded = o.getJSONObject("_shards").getInt("failed") == 0; + // {"_index":"historicalperformance24h","_type":"historicalperformance24h","_id":"CbZxvWwB4xjGPydc9ida","_version":1,"result":"created","_shards":{"total":4,"successful":1,"failed":0},"_seq_no":1,"_primary_term":1} + } - public boolean succeeded() { - return this.succeeded; - } + public boolean succeeded() { + return this.succeeded; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/SearchResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/SearchResponse.java index a5d2f1a36..6a7ed0d06 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/SearchResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/SearchResponse.java @@ -28,58 +28,60 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit; public class SearchResponse extends BaseResponse { - private long total; - private SearchHit[] searchHits; - private JSONObject aggregations; + private long total; + private SearchHit[] searchHits; + private JSONObject aggregations; - public SearchResponse(Response response) { - super(response); - this.handleResult(this.getJson(response)); - } + public SearchResponse(Response response) { + super(response); + this.handleResult(this.getJson(response)); + } - public SearchResponse(String json) { - super(null); - this.handleResult(this.getJson(json)); - } + public SearchResponse(String json) { + super(null); + this.handleResult(this.getJson(json)); + } - private void handleResult(JSONObject result) { - if(result!=null && this.isResponseSucceeded()) { - JSONObject hitsouter=result.getJSONObject("hits"); - this.total = hitsouter.getLong("total"); - JSONArray a=hitsouter.getJSONArray("hits"); - SearchHit[] hits=new SearchHit[a.length()]; - for(int i=0;i0; - } - public boolean hasFailures() { - return this.failures>0; - } - @Override - public String toString() { - return "UpdateByQueryResponse [isUpdated=" + isUpdated + ", failures=" + failures + "]"; - } + public UpdateByQueryResponse(Response response) { + super(response); + JSONObject o = this.getJson(response); + + this.isUpdated = o.getInt("updated"); + this.failures = o.getJSONArray("failures").length(); + //{"_index":"historicalperformance24h","_type":"historicalperformance24h","_id":"CbZxvWwB4xjGPydc9ida","_version":1,"result":"created","_shards":{"total":4,"successful":1,"failed":0},"_seq_no":1,"_primary_term":1} + } + + + public boolean isUpdated() { + return this.isUpdated > 0; + } + + public boolean hasFailures() { + return this.failures > 0; + } + + @Override + public String toString() { + return "UpdateByQueryResponse [isUpdated=" + isUpdated + ", failures=" + failures + "]"; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateResponse.java index 55f2652fa..80cb24872 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateResponse.java @@ -25,45 +25,34 @@ import org.elasticsearch.client.Response; import org.json.JSONObject; /** - { -"_index": "networkelement-connection-v1", -"_type": "networkelement-connection", -"_id": "sim2", -"_version": 2, -"result": "updated", -"_shards": { -"total": 2, -"successful": 1, -"failed": 0 -}, -"_seq_no": 5, -"_primary_term": 1 -} + * { "_index": "networkelement-connection-v1", "_type": "networkelement-connection", "_id": "sim2", "_version": 2, + * "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 5, "_primary_term": 1 } + * * @author jack * */ -public class UpdateResponse extends BaseResponse{ - - private String result; +public class UpdateResponse extends BaseResponse { + + private String result; + + public UpdateResponse(Response response) { + super(response); + JSONObject o = this.getJson(response); + + this.result = o.getString("result"); + } + + public boolean succeeded() { + if (this.result == null) { + return false; + } + String s = this.result.toLowerCase(); + return s.equals("updated") || s.equals("created"); + } - public UpdateResponse(Response response) { - super(response); - JSONObject o = this.getJson(response); - - this.result=o.getString("result"); - } - - public boolean succeeded() { - if(this.result==null) { - return false; - } - String s=this.result.toLowerCase(); - return s.equals("updated") || s.equals("created"); - } + @Override + public String toString() { + return "UpdateResponse [result=" + result + "]"; + } - @Override - public String toString() { - return "UpdateResponse [result=" + result + "]"; - } - } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java index bbdc505cd..809a44382 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/FileWatchdog.java @@ -26,8 +26,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Check every now and then that a certain file has not changed. If it has, then call the - * {@link #doOnChange} method. + * Check every now and then that a certain file has not changed. If it has, then call the {@link #doOnChange} method. * * @author JunHo Yoon * @since 3.1.1 @@ -78,7 +77,7 @@ public abstract class FileWatchdog extends Thread { try { fileExists = file.exists(); } catch (SecurityException e) { - LOGGER.warn("Was not allowed to read check file existence, file:[{}].",filename); + LOGGER.warn("Was not allowed to read check file existence, file:[{}].", filename); this.interrupt(); // there is no point in continuing return; } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomFile.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomFile.java index 092e65e60..2e0701257 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomFile.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomFile.java @@ -37,61 +37,64 @@ import org.xml.sax.SAXException; public class PomFile { - private Document xmlDoc; + private Document xmlDoc; - public PomFile(InputStream is) throws ParserConfigurationException, SAXException, IOException { - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory - .newInstance(); -// documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); -// documentBuilderFactory.setFeature(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); -// documentBuilderFactory.setFeature(XMLInputFactory.SUPPORT_DTD, false); + public PomFile(InputStream is) throws ParserConfigurationException, SAXException, IOException { + DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); + // documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + // documentBuilderFactory.setFeature(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); + // documentBuilderFactory.setFeature(XMLInputFactory.SUPPORT_DTD, false); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - this.xmlDoc = documentBuilder.parse(is); - } - - public String getProperty(String key) { - Node props = findChild("properties",this.xmlDoc.getDocumentElement()); - if(props!=null) { - Node prop = findChild(key, props); - if(prop!=null) { - return getTextValue(prop); - } - } - return null; - } - public String getParentVersion() { - Node parent = findChild("parent",this.xmlDoc.getDocumentElement()); - if(parent!=null) { - Node version = findChild("version", parent); - if(version!=null) { - return getTextValue(version); - } - } - return null; - } - private static String getTextValue(Node node) { - StringBuffer textValue = new StringBuffer(); - for (int i = 0,length = node.getChildNodes().getLength(); i < length; i ++) { - Node c = node.getChildNodes().item(i); - if (c.getNodeType() == Node.TEXT_NODE) { - textValue.append(c.getNodeValue()); - } - } - return textValue.toString().trim(); - } + DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + this.xmlDoc = documentBuilder.parse(is); + } + + public String getProperty(String key) { + Node props = findChild("properties", this.xmlDoc.getDocumentElement()); + if (props != null) { + Node prop = findChild(key, props); + if (prop != null) { + return getTextValue(prop); + } + } + return null; + } + + public String getParentVersion() { + Node parent = findChild("parent", this.xmlDoc.getDocumentElement()); + if (parent != null) { + Node version = findChild("version", parent); + if (version != null) { + return getTextValue(version); + } + } + return null; + } + + private static String getTextValue(Node node) { + StringBuffer textValue = new StringBuffer(); + for (int i = 0, length = node.getChildNodes().getLength(); i < length; i++) { + Node c = node.getChildNodes().item(i); + if (c.getNodeType() == Node.TEXT_NODE) { + textValue.append(c.getNodeValue()); + } + } + return textValue.toString().trim(); + } + + private Node findChild(String name, Node root) { + List childs = getChildElementNodes(root); + for (Element n : childs) { + if (name.equals(n.getNodeName())) { + return n; + } + } + return null; + } - private Node findChild(String name,Node root) { - List childs = getChildElementNodes(root); - for(Element n : childs) { - if(name.equals(n.getNodeName())) { - return n; - } - } - return null; - } - /** + /** * get all child nodes with type ELEMENT_NODE back in a list + * * @param node parent node * @return List with child nodes */ @@ -100,11 +103,11 @@ public class PomFile { NodeList childs = node.getChildNodes(); Node item; //System.out.println("Query node "+node.getNodeName()); - for (int n=0; n < childs.getLength(); n++) { + for (int n = 0; n < childs.getLength(); n++) { item = childs.item(n); //System.out.println(node.getNodeName()+"-"+item.getNodeName()+" "+item.getNodeType()); if (item.getNodeType() == Node.ELEMENT_NODE) { - res.add((Element)childs.item(n)); + res.add((Element) childs.item(n)); } } return res; diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomPropertiesFile.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomPropertiesFile.java index 20aa97199..3057dfe0a 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomPropertiesFile.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/file/PomPropertiesFile.java @@ -31,66 +31,66 @@ import java.util.Date; import java.util.Locale; /** - * Example Content: - * #Generated by org.apache.felix.bundleplugin - * #Tue Nov 19 10:17:57 CET 2019 - * version=0.7.0-SNAPSHOT - * groupId=org.onap.ccsdk.features.sdnr.wt -* artifactId=sdnr-wt-data-provider-provider + * Example Content: #Generated by org.apache.felix.bundleplugin #Tue Nov 19 10:17:57 CET 2019 version=0.7.0-SNAPSHOT + * groupId=org.onap.ccsdk.features.sdnr.wt artifactId=sdnr-wt-data-provider-provider + * * @author jack * */ public class PomPropertiesFile { - private Date buildDate; - private String version; - private String groupId; - private String artifactId; - - public Date getBuildDate() { - return this.buildDate; - } - public String getVersion() { - return this.version; - } - public String getGroupId() { - return this.groupId; - } - public String getArtifactId() { - return this.artifactId; - } - private final DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); - public PomPropertiesFile(InputStream is) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - int intRead; - while ((intRead = is.read()) != -1) { - bos.write(intRead); - } - this.parse(new String(bos.toByteArray())); - } + private Date buildDate; + private String version; + private String groupId; + private String artifactId; - private void parse(String s) { - String[] lines = s.split("\n"); - for(String line:lines) { - - if(line.startsWith("#Generated")) { - - } else if( line.startsWith("groupId")) { - this.groupId = line.substring("groupId=".length()); - } - else if(line.startsWith("artifactId")) { - this.artifactId = line.substring("artifactId=".length()); - } - else if(line.startsWith("#")){ - try { - this.buildDate = sdf.parse(line.substring(1)); - } catch (ParseException e) { - - } - } - if(version!=null && this.buildDate!=null && this.groupId!=null && this.artifactId!=null) { - break; - } - } - } + public Date getBuildDate() { + return this.buildDate; + } + + public String getVersion() { + return this.version; + } + + public String getGroupId() { + return this.groupId; + } + + public String getArtifactId() { + return this.artifactId; + } + + private final DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US); + + public PomPropertiesFile(InputStream is) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + int intRead; + while ((intRead = is.read()) != -1) { + bos.write(intRead); + } + this.parse(new String(bos.toByteArray())); + } + + private void parse(String s) { + String[] lines = s.split("\n"); + for (String line : lines) { + + if (line.startsWith("#Generated")) { + + } else if (line.startsWith("groupId")) { + this.groupId = line.substring("groupId=".length()); + } else if (line.startsWith("artifactId")) { + this.artifactId = line.substring("artifactId=".length()); + } else if (line.startsWith("#")) { + try { + this.buildDate = sdf.parse(line.substring(1)); + } catch (ParseException e) { + + } + } + if (version != null && this.buildDate != null && this.groupId != null && this.artifactId != null) { + break; + } + } + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPClient.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPClient.java index 169546a7e..fdba374c7 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPClient.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPClient.java @@ -86,10 +86,10 @@ public class BaseHTTPClient { } public BaseHTTPClient(String base, boolean trustAllCerts, String certFilename, String passphrase, int sslCertType) { - if(!base.endsWith("/")) { - base+="/"; + if (!base.endsWith("/")) { + base += "/"; } - this.baseUrl = base; + this.baseUrl = base; this.trustAll = trustAllCerts; try { sc = setupSsl(trustAll, certFilename, passphrase, sslCertType); diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPResponse.java index 1b844395b..91a2cc27c 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseHTTPResponse.java @@ -23,24 +23,23 @@ package org.onap.ccsdk.features.sdnr.wt.common.http; public class BaseHTTPResponse { - public static final int CODE404 = 404; - public static final int CODE200 = 200; - public static final BaseHTTPResponse UNKNOWN = new BaseHTTPResponse(-1, ""); - public final int code; - public final String body; + public static final int CODE404 = 404; + public static final int CODE200 = 200; + public static final BaseHTTPResponse UNKNOWN = new BaseHTTPResponse(-1, ""); + public final int code; + public final String body; - public BaseHTTPResponse(int code,String body) - { - this.code=code; - this.body=body; - } + public BaseHTTPResponse(int code, String body) { + this.code = code; + this.body = body; + } - @Override - public String toString() { - return "BaseHTTPResponse [code=" + code + ", body=" + body + "]"; - } + @Override + public String toString() { + return "BaseHTTPResponse [code=" + code + ", body=" + body + "]"; + } - public boolean isSuccess() { - return this.code==CODE200; - } + public boolean isSuccess() { + return this.code == CODE200; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java index b65984a58..59e4e7705 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/http/BaseServlet.java @@ -61,7 +61,9 @@ public abstract class BaseServlet extends HttpServlet { protected abstract boolean isOff(); protected abstract boolean doTrustAll(); + protected abstract void trustAll(boolean trust); + protected abstract String getRemoteUrl(String uri); /** @@ -74,7 +76,7 @@ public abstract class BaseServlet extends HttpServlet { sc = SSLContext.getInstance("TLSv1.2"); if (trustall) { if (trustCerts == null) { - trustCerts = new TrustManager[] { new javax.net.ssl.X509TrustManager() { + trustCerts = new TrustManager[] {new javax.net.ssl.X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; @@ -89,7 +91,7 @@ public abstract class BaseServlet extends HttpServlet { public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { // do not check anything when trust all } - } }; + }}; } } else { if (trustCerts != null) { @@ -101,7 +103,9 @@ public abstract class BaseServlet extends HttpServlet { } protected abstract boolean trustInsecure(); - protected abstract boolean isCorsEnabled(); + + protected abstract boolean isCorsEnabled(); + public BaseServlet() { this.trysslSetup(true); } @@ -117,7 +121,7 @@ public abstract class BaseServlet extends HttpServlet { */ private void trysslSetup(boolean force) { // if trustall config has changed - if (force || this.doTrustAll() != this.trustInsecure()) { + if (force || this.doTrustAll() != this.trustInsecure()) { this.trustAll(this.trustInsecure()); // resetup ssl config try { @@ -158,8 +162,7 @@ public abstract class BaseServlet extends HttpServlet { LOG.warn(e.getMessage()); } http.disconnect(); - } - else { + } else { this.set404Response(resp); } } @@ -184,8 +187,7 @@ public abstract class BaseServlet extends HttpServlet { LOG.warn(e.getMessage()); } http.disconnect(); - } - else { + } else { this.set404Response(resp); } } @@ -210,8 +212,7 @@ public abstract class BaseServlet extends HttpServlet { LOG.warn(e.getMessage()); } http.disconnect(); - } - else { + } else { this.set404Response(resp); } } @@ -236,8 +237,7 @@ public abstract class BaseServlet extends HttpServlet { LOG.warn(e.getMessage()); } http.disconnect(); - } - else { + } else { this.set404Response(resp); } } @@ -249,24 +249,24 @@ public abstract class BaseServlet extends HttpServlet { private URLConnection getConnection(HttpServletRequest req, final String method) throws IOException { - LOG.debug("{} Request to {}", method,req.getRequestURL()); + LOG.debug("{} Request to {}", method, req.getRequestURL()); String surl = this.getRemoteUrl(req.getRequestURI()); - if("GET".equals(method)) { + if ("GET".equals(method)) { Enumeration params = req.getParameterNames(); - if(params!=null) { + if (params != null) { String param; - if(params.hasMoreElements()) { - param=(String)params.nextElement(); - surl+="?"+param+"="+req.getParameter(param); + if (params.hasMoreElements()) { + param = (String) params.nextElement(); + surl += "?" + param + "=" + req.getParameter(param); } - while(params.hasMoreElements()) { - param=(String)params.nextElement(); - surl+="&"+param+"="+req.getParameter(param); + while (params.hasMoreElements()) { + param = (String) params.nextElement(); + surl += "&" + param + "=" + req.getParameter(param); } } } LOG.debug("RemoteURL: {}", surl); - if(surl==null) { + if (surl == null) { return null; } URL url = new URL(surl); @@ -284,7 +284,7 @@ public abstract class BaseServlet extends HttpServlet { String s = ""; Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { - String h = (String)headers.nextElement(); + String h = (String) headers.nextElement(); String v = req.getHeader(h); if (h != null && h.equals("Host")) { v = url.getAuthority(); diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/test/JSONAssert.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/test/JSONAssert.java index c845729a1..f95dfe0b2 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/test/JSONAssert.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/test/JSONAssert.java @@ -29,172 +29,173 @@ import org.json.JSONObject; public class JSONAssert { - /** - * nonstrict comparison means that json array items can be in different orders - */ - private static Comparator nonStrictComarator = new Comparator() { - - @Override - public int compare(JSONObject o1, JSONObject o2) { - if (o1.equals(o2)) { - return 0; - } - Iterator keys = o1.keys(); - while (keys.hasNext()) { - String key = String.valueOf(keys.next()); - int x = this.test(o1.get(key), o2.get(key)); - if (x != 0) { - return x; - } - } - return 0; - } - - private int test(Object o1, Object o2) { - int x; - if ((o1 instanceof Double) && (o2 instanceof Double)) { - - return (((Double) o1).doubleValue() - ((Double) o2).doubleValue()) < 0 ? -1 : 1; - } else if ((o1 instanceof Boolean) && (o2 instanceof Boolean)) { - return ((Boolean) o1).booleanValue() == ((Boolean) o2).booleanValue() ? 0 : -1; - - } else if ((o1 instanceof String) && (o2 instanceof String)) { - - return ((String) o1).equals(((String) o2)) ? 0 : -1; - } else if ((o1 instanceof JSONObject) && (o2 instanceof JSONObject)) { - if (((JSONObject) o1).length() != ((JSONObject) o2).length()) { - return ((JSONObject) o1).length() - ((JSONObject) o2).length() < 0 ? -1 : 1; - } - Iterator keys = ((JSONObject) o1).keys(); - while (keys.hasNext()) { - String key = String.valueOf(keys.next()); - if (!((JSONObject) o2).has(key)) { - return -1; - } - x = this.test(((JSONObject) o1).get(key), ((JSONObject) o2).get(key)); - if (x != 0) { - return x; - } - } - } else if ((o1 instanceof JSONArray) && (o2 instanceof JSONArray)) { - if (((JSONArray) o1).length() != ((JSONArray) o2).length()) { - return ((JSONArray) o1).length() - ((JSONArray) o2).length() < 0 ? -1 : 1; - } - for (int i = 0; i < ((JSONArray) o1).length(); i++) { - x = this.findInArray(((JSONArray) o1).get(i), (JSONArray) o2); - if (x != 0) { - return x; - } - } - for (int i = 0; i < ((JSONArray) o2).length(); i++) { - x = this.findInArray(((JSONArray) o2).get(i), (JSONArray) o1); - if (x != 0) { - return x; - } - } - } - return 0; - - } - - private int findInArray(Object node, JSONArray o) { - for (int i = 0; i < o.length(); i++) { - if (this.test(o.get(i), node) == 0) { - return 0; - } - } - return -1; - } - }; - /** - * strict comparison means that json array items have to be in the same order - */ - private static Comparator strictComarator = new Comparator() { - - @Override - public int compare(JSONObject o1, JSONObject o2) { - if (o1.equals(o2)) { - return 0; - } - Iterator keys = o1.keys(); - while (keys.hasNext()) { - String key = String.valueOf(keys.next()); - int x = this.test(o1.get(key), o2.get(key)); - if (x != 0) { - return x; - } - } - return 0; - } - - private int test(Object o1, Object o2) { - int x; - if ((o1 instanceof Double) && (o2 instanceof Double)) { - - return (((Double) o1).doubleValue() - ((Double) o2).doubleValue()) < 0 ? -1 : 1; - } else if ((o1 instanceof Boolean) && (o2 instanceof Boolean)) { - return ((Boolean) o1).booleanValue() == ((Boolean) o2).booleanValue() ? 0 : -1; - - } else if ((o1 instanceof String) && (o2 instanceof String)) { - - return ((String) o1).equals(((String) o2)) ? 0 : -1; - } else if ((o1 instanceof JSONObject) && (o2 instanceof JSONObject)) { - if (((JSONObject) o1).length() == 0 && ((JSONObject) o2).length() == 0) { - return 0; - } - Iterator keys = ((JSONObject) o1).keys(); - while (keys.hasNext()) { - String key = String.valueOf(keys.next()); - if (!((JSONObject) o2).has(key)) { - return -1; - } - x = this.test(((JSONObject) o1).get(key), ((JSONObject) o2).get(key)); - if (x != 0) { - return x; - } - } - } else if ((o1 instanceof JSONArray) && (o2 instanceof JSONArray)) { - if (((JSONArray) o1).length() != ((JSONArray) o2).length()) { - return ((JSONArray) o1).length() - ((JSONArray) o2).length() < 0 ? -1 : 1; - } - for (int i = 0; i < ((JSONArray) o1).length(); i++) { - x = this.test(((JSONArray) o1).get(i), ((JSONArray) o2).get(i)); - if (x != 0) { - return x; - } - } - } - return 0; - - } - }; - public static void assertEquals(String def, String toTest, boolean strict) throws JSONException { - assertEquals(null, def, toTest, strict); - } - - public static void assertEquals(String message, String def, String toTest, boolean strict) throws JSONException { - if (strict) { - assertEqualsStrict(message, def, toTest); - } else { - assertEqualsNonStrict(message, def, toTest); - } - } - - private static void assertEqualsNonStrict(String message, String def, String toTest) throws JSONException { - - JSONObject d1 = new JSONObject(def); - JSONObject d2 = new JSONObject(toTest); - if (nonStrictComarator.compare(d1, d2) != 0) { - throw new AssertionError(message); - } - } - - private static void assertEqualsStrict(String message, String def, String toTest) throws JSONException { - JSONObject d1 = new JSONObject(def); - JSONObject d2 = new JSONObject(toTest); - if (strictComarator.compare(d1, d2) != 0) { - throw new AssertionError(message); - } - } + /** + * nonstrict comparison means that json array items can be in different orders + */ + private static Comparator nonStrictComarator = new Comparator() { + + @Override + public int compare(JSONObject o1, JSONObject o2) { + if (o1.equals(o2)) { + return 0; + } + Iterator keys = o1.keys(); + while (keys.hasNext()) { + String key = String.valueOf(keys.next()); + int x = this.test(o1.get(key), o2.get(key)); + if (x != 0) { + return x; + } + } + return 0; + } + + private int test(Object o1, Object o2) { + int x; + if ((o1 instanceof Double) && (o2 instanceof Double)) { + + return (((Double) o1).doubleValue() - ((Double) o2).doubleValue()) < 0 ? -1 : 1; + } else if ((o1 instanceof Boolean) && (o2 instanceof Boolean)) { + return ((Boolean) o1).booleanValue() == ((Boolean) o2).booleanValue() ? 0 : -1; + + } else if ((o1 instanceof String) && (o2 instanceof String)) { + + return ((String) o1).equals(((String) o2)) ? 0 : -1; + } else if ((o1 instanceof JSONObject) && (o2 instanceof JSONObject)) { + if (((JSONObject) o1).length() != ((JSONObject) o2).length()) { + return ((JSONObject) o1).length() - ((JSONObject) o2).length() < 0 ? -1 : 1; + } + Iterator keys = ((JSONObject) o1).keys(); + while (keys.hasNext()) { + String key = String.valueOf(keys.next()); + if (!((JSONObject) o2).has(key)) { + return -1; + } + x = this.test(((JSONObject) o1).get(key), ((JSONObject) o2).get(key)); + if (x != 0) { + return x; + } + } + } else if ((o1 instanceof JSONArray) && (o2 instanceof JSONArray)) { + if (((JSONArray) o1).length() != ((JSONArray) o2).length()) { + return ((JSONArray) o1).length() - ((JSONArray) o2).length() < 0 ? -1 : 1; + } + for (int i = 0; i < ((JSONArray) o1).length(); i++) { + x = this.findInArray(((JSONArray) o1).get(i), (JSONArray) o2); + if (x != 0) { + return x; + } + } + for (int i = 0; i < ((JSONArray) o2).length(); i++) { + x = this.findInArray(((JSONArray) o2).get(i), (JSONArray) o1); + if (x != 0) { + return x; + } + } + } + return 0; + + } + + private int findInArray(Object node, JSONArray o) { + for (int i = 0; i < o.length(); i++) { + if (this.test(o.get(i), node) == 0) { + return 0; + } + } + return -1; + } + }; + /** + * strict comparison means that json array items have to be in the same order + */ + private static Comparator strictComarator = new Comparator() { + + @Override + public int compare(JSONObject o1, JSONObject o2) { + if (o1.equals(o2)) { + return 0; + } + Iterator keys = o1.keys(); + while (keys.hasNext()) { + String key = String.valueOf(keys.next()); + int x = this.test(o1.get(key), o2.get(key)); + if (x != 0) { + return x; + } + } + return 0; + } + + private int test(Object o1, Object o2) { + int x; + if ((o1 instanceof Double) && (o2 instanceof Double)) { + + return (((Double) o1).doubleValue() - ((Double) o2).doubleValue()) < 0 ? -1 : 1; + } else if ((o1 instanceof Boolean) && (o2 instanceof Boolean)) { + return ((Boolean) o1).booleanValue() == ((Boolean) o2).booleanValue() ? 0 : -1; + + } else if ((o1 instanceof String) && (o2 instanceof String)) { + + return ((String) o1).equals(((String) o2)) ? 0 : -1; + } else if ((o1 instanceof JSONObject) && (o2 instanceof JSONObject)) { + if (((JSONObject) o1).length() == 0 && ((JSONObject) o2).length() == 0) { + return 0; + } + Iterator keys = ((JSONObject) o1).keys(); + while (keys.hasNext()) { + String key = String.valueOf(keys.next()); + if (!((JSONObject) o2).has(key)) { + return -1; + } + x = this.test(((JSONObject) o1).get(key), ((JSONObject) o2).get(key)); + if (x != 0) { + return x; + } + } + } else if ((o1 instanceof JSONArray) && (o2 instanceof JSONArray)) { + if (((JSONArray) o1).length() != ((JSONArray) o2).length()) { + return ((JSONArray) o1).length() - ((JSONArray) o2).length() < 0 ? -1 : 1; + } + for (int i = 0; i < ((JSONArray) o1).length(); i++) { + x = this.test(((JSONArray) o1).get(i), ((JSONArray) o2).get(i)); + if (x != 0) { + return x; + } + } + } + return 0; + + } + }; + + public static void assertEquals(String def, String toTest, boolean strict) throws JSONException { + assertEquals(null, def, toTest, strict); + } + + public static void assertEquals(String message, String def, String toTest, boolean strict) throws JSONException { + if (strict) { + assertEqualsStrict(message, def, toTest); + } else { + assertEqualsNonStrict(message, def, toTest); + } + } + + private static void assertEqualsNonStrict(String message, String def, String toTest) throws JSONException { + + JSONObject d1 = new JSONObject(def); + JSONObject d2 = new JSONObject(toTest); + if (nonStrictComarator.compare(d1, d2) != 0) { + throw new AssertionError(message); + } + } + + private static void assertEqualsStrict(String message, String def, String toTest) throws JSONException { + JSONObject d1 = new JSONObject(def); + JSONObject d2 = new JSONObject(toTest); + if (strictComarator.compare(d1, d2) != 0) { + throw new AssertionError(message); + } + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/Environment.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/Environment.java index a2ef92910..050152f50 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/Environment.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/Environment.java @@ -27,24 +27,22 @@ import java.util.Map; public class Environment { - public static String getVar(String v) - { - if(v.equals("$HOSTNAME")) - { - String s=null; - try { - s = Inet4Address.getLocalHost().getHostName(); - } catch (UnknownHostException e) { + public static String getVar(String v) { + if (v.equals("$HOSTNAME")) { + String s = null; + try { + s = Inet4Address.getLocalHost().getHostName(); + } catch (UnknownHostException e) { - } - if(s!=null && s.length()>0) - return s; - } - Map env = System.getenv(); + } + if (s != null && s.length() > 0) + return s; + } + Map env = System.getenv(); for (String envName : env.keySet()) { - if(envName!=null && envName.equals(v)) - return env.get(envName); + if (envName != null && envName.equals(v)) + return env.get(envName); } return null; - } + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/ResourceFileLoader.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/ResourceFileLoader.java index 739ffb35f..208957a53 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/ResourceFileLoader.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/ResourceFileLoader.java @@ -25,9 +25,9 @@ import java.io.File; public class ResourceFileLoader { - public static File getFile(Object o, String fileName) { - ClassLoader classLoader = o.getClass().getClassLoader(); - return new File(classLoader.getResource(fileName).getFile()); - } + public static File getFile(Object o, String fileName) { + ClassLoader classLoader = o.getClass().getClassLoader(); + return new File(classLoader.getResource(fileName).getFile()); + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/StackTrace.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/StackTrace.java index ee17c55f7..5826285db 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/StackTrace.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/util/StackTrace.java @@ -32,6 +32,7 @@ public class StackTrace { /** * Return stacktrace as String + * * @param e with stacktrace information to be converte * @return String with call stack */ -- cgit 1.2.3-korg