diff options
author | highstreetherbert <herbert.eiselt@highstreet-technologies.com> | 2020-07-10 15:30:18 +0200 |
---|---|---|
committer | highstreetherbert <herbert.eiselt@highstreet-technologies.com> | 2020-07-10 16:41:17 +0200 |
commit | 8f9aa1fb011ed22c60a662d647c4e4ae4c5c6560 (patch) | |
tree | 271d51436e94fa92e388ff49f962355a6807719f /sdnr | |
parent | 23c27ddcd79913d11eac16eb42c5a43899de97a1 (diff) |
Reformat sdnr common to ONAP code style
Reformat to ONAP code style
Issue-ID: SDNC-1272
Signed-off-by: highstreetherbert <herbert.eiselt@highstreet-technologies.com>
Change-Id: I4ac9bf101fbd679e582ffcdfdc5959278ad1c5ec
Signed-off-by: highstreetherbert <herbert.eiselt@highstreet-technologies.com>
Diffstat (limited to 'sdnr')
96 files changed, 4291 insertions, 4287 deletions
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<T> { - } - - 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<T> { + } + + 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<String, Section> sections; - // end of variables - - // constructors - public ConfigurationFileRepresentation(File f) { - - this.mFile = f; - this.sections = new HashMap<String, Section>(); - 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<Section> 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<Section> 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<Section> 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<Section> os = this.getSection(section); - if (os.isPresent()) { - return os.get().getProperty(propertyKey); - } else { - LOG.debug("Unknown configuration section {}", section); - return EMPTY; - } - } - - public synchronized Optional<Long> getPropertyLong(String section, String propertyKey) { - Optional<Section> 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<Section> 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<String, Section> sections; + // end of variables + + // constructors + public ConfigurationFileRepresentation(File f) { + + this.mFile = f; + this.sections = new HashMap<String, Section>(); + 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<Section> 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<Section> 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<Section> 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<Section> os = this.getSection(section); + if (os.isPresent()) { + return os.get().getProperty(propertyKey); + } else { + LOG.debug("Unknown configuration section {}", section); + return EMPTY; + } + } + + public synchronized Optional<Long> getPropertyLong(String section, String propertyKey) { + Optional<Section> 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<Section> 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<String> rawLines; private final LinkedHashMap<String, SectionValue> 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<String> 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<String> comments; private boolean isUncommented; @@ -48,40 +49,40 @@ class SectionValue { } public SectionValue(String value, boolean isUncommented) { - this(value, new ArrayList<String>(), isUncommented); - } + this(value, new ArrayList<String>(), 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<String> 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<String> 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<SearchHit> 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<SearchHit> 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<SearchHit> doReadAllJsonData(String dataTypeName, boolean ignoreException); - /** - * @param alias - * @param dataTypeName - * @param queryBuilder - * @param ignoreException - * @return - */ - SearchResult<SearchHit> doReadByQueryJsonData(String alias, String dataTypeName, QueryBuilder queryBuilder, - boolean ignoreException); + /** + * @param alias + * @param dataTypeName + * @param queryBuilder + * @param ignoreException + * @return + */ + SearchResult<SearchHit> 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<SearchHit> doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder) { + + return this.doReadByQueryJsonData(dataTypeName, queryBuilder, false); } - @Override - public @Nonnull SearchResult<SearchHit> doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder) { - - return this.doReadByQueryJsonData(dataTypeName, queryBuilder, false); - } - @Override - public @Nonnull SearchResult<SearchHit> doReadByQueryJsonData( String dataTypeName,QueryBuilder queryBuilder, boolean ignoreException) { - return this.doReadByQueryJsonData(dataTypeName, dataTypeName,queryBuilder,ignoreException); - } - @Override - public @Nonnull SearchResult<SearchHit> 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<SearchHit>(response != null ? response.getHits() : new SearchHit[] {}, total); - } - @Override - public @Nonnull SearchResult<SearchHit> doReadAllJsonData(String dataTypeName) { - return this.doReadAllJsonData( dataTypeName,false); - } @Override - public @Nonnull SearchResult<SearchHit> doReadAllJsonData( String dataTypeName, boolean ignoreException) { - return doReadByQueryJsonData( dataTypeName, QueryBuilders.matchAllQuery(),ignoreException); - } - - public @Nonnull SearchResult<SearchHit> 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<String> 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<SearchHit> doReadByQueryJsonData(String dataTypeName, QueryBuilder queryBuilder, + boolean ignoreException) { + return this.doReadByQueryJsonData(dataTypeName, dataTypeName, queryBuilder, ignoreException); + } + + @Override + public @Nonnull SearchResult<SearchHit> 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<SearchHit>(response != null ? response.getHits() : new SearchHit[] {}, total); + } + + @Override + public @Nonnull SearchResult<SearchHit> doReadAllJsonData(String dataTypeName) { + return this.doReadAllJsonData(dataTypeName, false); + } + + @Override + public @Nonnull SearchResult<SearchHit> doReadAllJsonData(String dataTypeName, boolean ignoreException) { + return doReadByQueryJsonData(dataTypeName, QueryBuilders.matchAllQuery(), ignoreException); + } + + public @Nonnull SearchResult<SearchHit> 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<String> 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<T> { - /** - * objects in results - */ - private final List<T> hits; - /** - * size of all potential hits - * not necessarily the number of hits - */ - private long total; + /** + * objects in results + */ + private final List<T> 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<T> hits,long total) { -// this.hits = hits; -// this.total = total; -// } - public SearchResult() { - this.hits=new ArrayList<>(); - this.total = 0; - } - public List<T> 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<T> hits,long total) { + // this.hits = hits; + // this.total = total; + // } + public SearchResult() { + this.hits = new ArrayList<>(); + this.total = 0; + } + + public List<T> 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<AliasesEntry>{ +public class AliasesEntryList extends ArrayList<AliasesEntry> { - /** - * - */ - 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<String> getLinkedIndices() { - List<String> list = new ArrayList<String>(); - for(AliasesEntry e:this) { - list.add(e.getIndex()); - } - return list; - } + /** + * @return + */ + public List<String> getLinkedIndices() { + List<String> list = new ArrayList<String>(); + 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.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; - } - } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntry.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntry.java index 26e088d3f..b31ff4389 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntry.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntry.java @@ -28,97 +28,99 @@ import java.util.regex.Pattern; /** * @author Michael Dürre * - * Entry of list indices http request (/_cat/indices) - * - * yellow open inventoryequipment-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb + * Entry of list indices http request (/_cat/indices) + * + * yellow open inventoryequipment-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb */ public class IndicesEntry { - private static final String regex = "^(yellow|red|green)[\\ ]+([^\\ ]*)[\\ ]+([^\\ ]*)[\\ ]+([^\\ ]*)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([^\\ ]+)[\\ ]+([^\\ ]+)$"; - private static final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); - //for ES 2.2.0 - private static final String regexOld = "^(yellow|red|green)[\\ ]+([^\\ ]*)[\\ ]+([^\\ ]*)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([^\\ ]+)[\\ ]+([^\\ ]+)$"; - private static final Pattern patternOld = Pattern.compile(regexOld, Pattern.MULTILINE); + private static final String regex = + "^(yellow|red|green)[\\ ]+([^\\ ]*)[\\ ]+([^\\ ]*)[\\ ]+([^\\ ]*)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([^\\ ]+)[\\ ]+([^\\ ]+)$"; + private static final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); + //for ES 2.2.0 + private static final String regexOld = + "^(yellow|red|green)[\\ ]+([^\\ ]*)[\\ ]+([^\\ ]*)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([0-9]+)[\\ ]+([^\\ ]+)[\\ ]+([^\\ ]+)$"; + private static final Pattern patternOld = Pattern.compile(regexOld, Pattern.MULTILINE); - private final String status; - private final String status2; - private final String name; - private final String hash; - private final int shards; - private final int replicas; - private final int c1; - private final int c2; - private final String size1; - private final String size2; + private final String status; + private final String status2; + private final String name; + private final String hash; + private final int shards; + private final int replicas; + private final int c1; + private final int c2; + private final String size1; + private final String size2; - public String getStatus() { - return status; - } + public String getStatus() { + return status; + } - public String getStatus2() { - return status2; - } + public String getStatus2() { + return status2; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getHash() { - return hash; - } + public String getHash() { + return hash; + } - public int getShards() { - return shards; - } + public int getShards() { + return shards; + } - public int getReplicas() { - return replicas; - } + public int getReplicas() { + return replicas; + } - public int getC1() { - return c1; - } + public int getC1() { + return c1; + } - public int getC2() { - return c2; - } + public int getC2() { + return c2; + } - public String getSize1() { - return size1; - } + public String getSize1() { + return size1; + } - public String getSize2() { - return size2; - } + public String getSize2() { + return size2; + } - public IndicesEntry(String line) throws ParseException { - Matcher matcher = pattern.matcher(line.trim()); - if (!matcher.find() || matcher.groupCount() < 10) { - matcher = patternOld.matcher(line.trim()); - if (!matcher.find() || matcher.groupCount() < 9) { - throw new ParseException("unable to parse string:" + line, 0); - } - this.status = matcher.group(1); - this.status2 = matcher.group(2); - this.name = matcher.group(3); - this.hash = ""; - this.shards = Integer.parseInt(matcher.group(4)); - this.replicas = Integer.parseInt(matcher.group(5)); - this.c1 = Integer.parseInt(matcher.group(6)); - this.c2 = Integer.parseInt(matcher.group(7)); - this.size1 = matcher.group(8); - this.size2 = matcher.group(9); - } else { - this.status = matcher.group(1); - this.status2 = matcher.group(2); - this.name = matcher.group(3); - this.hash = matcher.group(4); - this.shards = Integer.parseInt(matcher.group(5)); - this.replicas = Integer.parseInt(matcher.group(6)); - this.c1 = Integer.parseInt(matcher.group(7)); - this.c2 = Integer.parseInt(matcher.group(8)); - this.size1 = matcher.group(9); - this.size2 = matcher.group(10); - } - } + public IndicesEntry(String line) throws ParseException { + Matcher matcher = pattern.matcher(line.trim()); + if (!matcher.find() || matcher.groupCount() < 10) { + matcher = patternOld.matcher(line.trim()); + if (!matcher.find() || matcher.groupCount() < 9) { + throw new ParseException("unable to parse string:" + line, 0); + } + this.status = matcher.group(1); + this.status2 = matcher.group(2); + this.name = matcher.group(3); + this.hash = ""; + this.shards = Integer.parseInt(matcher.group(4)); + this.replicas = Integer.parseInt(matcher.group(5)); + this.c1 = Integer.parseInt(matcher.group(6)); + this.c2 = Integer.parseInt(matcher.group(7)); + this.size1 = matcher.group(8); + this.size2 = matcher.group(9); + } else { + this.status = matcher.group(1); + this.status2 = matcher.group(2); + this.name = matcher.group(3); + this.hash = matcher.group(4); + this.shards = Integer.parseInt(matcher.group(5)); + this.replicas = Integer.parseInt(matcher.group(6)); + this.c1 = Integer.parseInt(matcher.group(7)); + this.c2 = Integer.parseInt(matcher.group(8)); + this.size1 = matcher.group(9); + this.size2 = matcher.group(10); + } + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntryList.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntryList.java index 5431db9e7..7b736835f 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntryList.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/data/IndicesEntryList.java @@ -28,38 +28,38 @@ import java.util.List; * @author Michael Dürre * */ -public class IndicesEntryList extends ArrayList<IndicesEntry>{ +public class IndicesEntryList extends ArrayList<IndicesEntry> { - /** - * - */ - 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<String> 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<String> 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<String> 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<String> onlyForInsert) { - if (onlyForInsert == null) { - onlyForInsert = new ArrayList<String>(); - } - 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<String> 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<String> onlyForInsert) { + if (onlyForInsert == null) { + onlyForInsert = new ArrayList<String>(); + } + 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<String,Long>{ +public class AggregationEntries extends LinkedHashMap<String, Long> { - 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<String> with selected values - */ - public String[] getKeysAsPagedStringList(long size, long offset) { - List<String> ltps = new ArrayList<String>(); - 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<String> with selected values + */ + public String[] getKeysAsPagedStringList(long size, long offset) { + List<String> ltps = new ArrayList<String>(); + 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<String> getLines(Response response){ - return this.getLines(response,true); - } - List<String> getLines(Response response,boolean ignoreEmpty) { - try { - String sresponse = EntityUtils.toString(response.getEntity()); - LOG.debug("parsing response={}", sresponse); - String[] hlp = sresponse.split("\n"); - List<String> lines=new ArrayList<String>(); - 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<String> getLines(Response response) { + return this.getLines(response, true); + } - } + List<String> getLines(Response response, boolean ignoreEmpty) { + try { + String sresponse = EntityUtils.toString(response.getEntity()); + LOG.debug("parsing response={}", sresponse); + String[] hlp = sresponse.split("\n"); + List<String> lines = new ArrayList<String>(); + 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<String> lines=this.getLines(response); + List<String> 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<String> lines=this.getLines(response); + List<String> 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<String,NodeStats> nodeStats; - - public NodesInfo getNodesInfo() { - return this.nodesInfo; - } - public Map<String,NodeStats> 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<String, NodeStats> nodeStats; + + public NodesInfo getNodesInfo() { + return this.nodesInfo; + } + + public Map<String, NodeStats> 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;i<a.length();i++) { - hits[i]=new SearchHit(a.getJSONObject(i)); - } - this.searchHits=hits; - if(result.has("aggregations")) { - this.aggregations = result.getJSONObject("aggregations"); - } - else { - this.aggregations=null; - } - } - else { - this.searchHits=new SearchHit[0]; - } - } - public SearchHit[] getHits() { - return this.searchHits; - } - public long getTotal() { - return this.total; - } - public boolean hasAggregations() { - return this.aggregations!=null; - } - public AggregationEntries getAggregations(String property) { - AggregationEntries entries=new AggregationEntries(); - if(this.aggregations!=null && this.aggregations.has(property)) { - JSONArray a=this.aggregations.getJSONObject(property).getJSONArray("buckets"); - for(int i=0;i<a.length();i++) { - entries.put(a.getJSONObject(i).getString("key"),a.getJSONObject(i).getLong("doc_count") ); - } - } - return entries; - } + 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; i < a.length(); i++) { + hits[i] = new SearchHit(a.getJSONObject(i)); + } + this.searchHits = hits; + if (result.has("aggregations")) { + this.aggregations = result.getJSONObject("aggregations"); + } else { + this.aggregations = null; + } + } else { + this.searchHits = new SearchHit[0]; + } + } + + public SearchHit[] getHits() { + return this.searchHits; + } + + public long getTotal() { + return this.total; + } + + public boolean hasAggregations() { + return this.aggregations != null; + } + + public AggregationEntries getAggregations(String property) { + AggregationEntries entries = new AggregationEntries(); + if (this.aggregations != null && this.aggregations.has(property)) { + JSONArray a = this.aggregations.getJSONObject(property).getJSONArray("buckets"); + for (int i = 0; i < a.length(); i++) { + entries.put(a.getJSONObject(i).getString("key"), a.getJSONObject(i).getLong("doc_count")); + } + } + return entries; + } } diff --git a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateByQueryResponse.java b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateByQueryResponse.java index 7d70f52fa..761b3c7c2 100644 --- a/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateByQueryResponse.java +++ b/sdnr/wt/common/src/main/java/org/onap/ccsdk/features/sdnr/wt/common/database/responses/UpdateByQueryResponse.java @@ -25,50 +25,39 @@ import org.elasticsearch.client.Response; import org.json.JSONObject; /** - * { - * "took":47, - * "timed_out":false, - * "total":1, - * "updated":1, - * "deleted":0, - * "batches":1, - * "version_conflicts":0, - * "noops":0, - * "retries":{ - * "bulk":0, - * "search":0 - * }, - * "throttled_millis":0, - * "requests_per_second":-1.0, - * "throttled_until_millis":0, - * "failures":[]} + * { "took":47, "timed_out":false, "total":1, "updated":1, "deleted":0, "batches":1, "version_conflicts":0, "noops":0, + * "retries":{ "bulk":0, "search":0 }, "throttled_millis":0, "requests_per_second":-1.0, "throttled_until_millis":0, + * "failures":[]} + * * @author jack * */ -public class UpdateByQueryResponse extends BaseResponse{ +public class UpdateByQueryResponse extends BaseResponse { - - private int isUpdated; - private int 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} - } + private int isUpdated; + private int failures; - - public boolean isUpdated() { - return this.isUpdated>0; - } - 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<Element> childs = getChildElementNodes(root); + for (Element n : childs) { + if (name.equals(n.getNodeName())) { + return n; + } + } + return null; + } - private Node findChild(String name,Node root) { - List<Element> 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<JSONObject> nonStrictComarator = new Comparator<JSONObject>() { - - @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<JSONObject> strictComarator = new Comparator<JSONObject>() { - - @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<JSONObject> nonStrictComarator = new Comparator<JSONObject>() { + + @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<JSONObject> strictComarator = new Comparator<JSONObject>() { + + @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<String, String> env = System.getenv(); + } + if (s != null && s.length() > 0) + return s; + } + Map<String, String> 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 */ diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java index 57ae0e3bc..3584d7f28 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseHttpClient.java @@ -47,141 +47,139 @@ import com.sun.net.httpserver.HttpServer; @SuppressWarnings("restriction") public class TestBaseHttpClient { - public static final String HTTPMETHOD_GET = "GET"; - public static final String HTTPMETHOD_POST = "POST"; - public static final String HTTPMETHOD_PUT = "PUT"; - public static final String HTTPMETHOD_DELETE = "DELETE"; - public static final String HTTPMETHOD_OPTIONS = "OPTIONS"; - public static final String RESPONSE_GET = "This is the response get"; - public static final String RESPONSE_POST = "This is the response post"; - public static final String RESPONSE_PUT = "This is the response put"; - public static final String RESPONSE_DELETE = "This is the response delete"; - public static final String RESPONSE_OPTIONS = "This is the response options"; - private static final String TESTURI = "/mwtn/test"; - private static HttpServer server; - private static ExecutorService httpThreadPool; - private static final int testPort = 54440; - - @Test - public void test() { - MyHttpClient httpClient = new MyHttpClient("http://localhost:"+testPort, true); - Map<String, String> headers = new HashMap<String,String>(); - headers.put("Authorization", BaseHTTPClient.getAuthorizationHeaderValue("admin", "admin")); - headers.put("Content-Type","application/json"); - BaseHTTPResponse response=null; - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_GET, null, headers ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals(RESPONSE_GET, response.body); - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_POST, "{}", headers ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.isSuccess()); - System.out.println(response.toString()); - assertEquals(RESPONSE_POST, response.body); - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_PUT, "{}", headers ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals(RESPONSE_PUT, response.body); - try { - response= httpClient.sendRequest(TESTURI, HTTPMETHOD_DELETE, "{}", headers ); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals(RESPONSE_DELETE, response.body); - - } - - - - - @BeforeClass - public static void initTestWebserver() throws IOException { - server = HttpServer.create(new InetSocketAddress("127.0.0.1", testPort), 0); - httpThreadPool = Executors.newFixedThreadPool(5); - server.setExecutor(httpThreadPool); - server.createContext(TESTURI, new MyHandler()); - //server.createContext("/", new MyRootHandler()); - server.setExecutor(null); // creates a default executor - server.start(); - System.out.println("http server started"); - } - @AfterClass - public static void stopTestWebserver() { - System.out.println("try to stop server"); - if (server != null) { - server.stop(0); - httpThreadPool.shutdownNow(); - System.out.println("http server stopped" ); - } - } - - private class MyHttpClient extends BaseHTTPClient{ - - public MyHttpClient(String base, boolean trustAllCerts) { - super(base, trustAllCerts); - } - - @Override - public BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers) - throws IOException { - return super.sendRequest(uri, method, body, headers); - } - } - - public static class MyHandler implements HttpHandler { - - @Override - public void handle(HttpExchange t) throws IOException { - String method = t.getRequestMethod(); - System.out.println(String.format("req received: %s %s" ,method,t.getRequestURI())); - OutputStream os = null; - try { - if (method.equals(HTTPMETHOD_GET)) { - t.sendResponseHeaders(200, RESPONSE_GET.length()); - os = t.getResponseBody(); - os.write(RESPONSE_GET.getBytes()); - } else if (method.equals(HTTPMETHOD_POST)) { - t.sendResponseHeaders(200, RESPONSE_POST.length()); - os = t.getResponseBody(); - os.write(RESPONSE_POST.getBytes()); - } else if (method.equals(HTTPMETHOD_PUT)) { - t.sendResponseHeaders(200, RESPONSE_PUT.length()); - os = t.getResponseBody(); - os.write(RESPONSE_PUT.getBytes()); - } else if (method.equals(HTTPMETHOD_DELETE)) { - t.sendResponseHeaders(200, RESPONSE_DELETE.length()); - os = t.getResponseBody(); - os.write(RESPONSE_DELETE.getBytes()); - } else if (method.equals(HTTPMETHOD_OPTIONS)) { - t.sendResponseHeaders(200, RESPONSE_OPTIONS.length()); - //os = t.getResponseBody(); - //os.write(RESPONSE_OPTIONS.getBytes()); - } else { - t.sendResponseHeaders(404, 0); - } - System.out.println("req handled successful"); - - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finally { - if (os != null) - { - os.flush(); - os.close(); - } - } - } - } + public static final String HTTPMETHOD_GET = "GET"; + public static final String HTTPMETHOD_POST = "POST"; + public static final String HTTPMETHOD_PUT = "PUT"; + public static final String HTTPMETHOD_DELETE = "DELETE"; + public static final String HTTPMETHOD_OPTIONS = "OPTIONS"; + public static final String RESPONSE_GET = "This is the response get"; + public static final String RESPONSE_POST = "This is the response post"; + public static final String RESPONSE_PUT = "This is the response put"; + public static final String RESPONSE_DELETE = "This is the response delete"; + public static final String RESPONSE_OPTIONS = "This is the response options"; + private static final String TESTURI = "/mwtn/test"; + private static HttpServer server; + private static ExecutorService httpThreadPool; + private static final int testPort = 54440; + + @Test + public void test() { + MyHttpClient httpClient = new MyHttpClient("http://localhost:" + testPort, true); + Map<String, String> headers = new HashMap<String, String>(); + headers.put("Authorization", BaseHTTPClient.getAuthorizationHeaderValue("admin", "admin")); + headers.put("Content-Type", "application/json"); + BaseHTTPResponse response = null; + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_GET, null, headers); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_GET, response.body); + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_POST, "{}", headers); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.isSuccess()); + System.out.println(response.toString()); + assertEquals(RESPONSE_POST, response.body); + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_PUT, "{}", headers); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_PUT, response.body); + try { + response = httpClient.sendRequest(TESTURI, HTTPMETHOD_DELETE, "{}", headers); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals(RESPONSE_DELETE, response.body); + + } + + + + @BeforeClass + public static void initTestWebserver() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", testPort), 0); + httpThreadPool = Executors.newFixedThreadPool(5); + server.setExecutor(httpThreadPool); + server.createContext(TESTURI, new MyHandler()); + //server.createContext("/", new MyRootHandler()); + server.setExecutor(null); // creates a default executor + server.start(); + System.out.println("http server started"); + } + + @AfterClass + public static void stopTestWebserver() { + System.out.println("try to stop server"); + if (server != null) { + server.stop(0); + httpThreadPool.shutdownNow(); + System.out.println("http server stopped"); + } + } + + private class MyHttpClient extends BaseHTTPClient { + + public MyHttpClient(String base, boolean trustAllCerts) { + super(base, trustAllCerts); + } + + @Override + public BaseHTTPResponse sendRequest(String uri, String method, String body, Map<String, String> headers) + throws IOException { + return super.sendRequest(uri, method, body, headers); + } + } + + public static class MyHandler implements HttpHandler { + + @Override + public void handle(HttpExchange t) throws IOException { + String method = t.getRequestMethod(); + System.out.println(String.format("req received: %s %s", method, t.getRequestURI())); + OutputStream os = null; + try { + if (method.equals(HTTPMETHOD_GET)) { + t.sendResponseHeaders(200, RESPONSE_GET.length()); + os = t.getResponseBody(); + os.write(RESPONSE_GET.getBytes()); + } else if (method.equals(HTTPMETHOD_POST)) { + t.sendResponseHeaders(200, RESPONSE_POST.length()); + os = t.getResponseBody(); + os.write(RESPONSE_POST.getBytes()); + } else if (method.equals(HTTPMETHOD_PUT)) { + t.sendResponseHeaders(200, RESPONSE_PUT.length()); + os = t.getResponseBody(); + os.write(RESPONSE_PUT.getBytes()); + } else if (method.equals(HTTPMETHOD_DELETE)) { + t.sendResponseHeaders(200, RESPONSE_DELETE.length()); + os = t.getResponseBody(); + os.write(RESPONSE_DELETE.getBytes()); + } else if (method.equals(HTTPMETHOD_OPTIONS)) { + t.sendResponseHeaders(200, RESPONSE_OPTIONS.length()); + //os = t.getResponseBody(); + //os.write(RESPONSE_OPTIONS.getBytes()); + } else { + t.sendResponseHeaders(404, 0); + } + System.out.println("req handled successful"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } finally { + if (os != null) { + os.flush(); + os.close(); + } + } + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java index 02a82a70d..0c1ae50ee 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestBaseServlet.java @@ -35,40 +35,43 @@ import org.onap.ccsdk.features.sdnr.wt.common.test.helper.HelpServletBase; * @author Michael Dürre * */ -public class TestBaseServlet extends HelpServletBase{ +public class TestBaseServlet extends HelpServletBase { - private static final int PORT = 40003; - public TestBaseServlet() { - super("/base",PORT); - } - - @Test - public void test() throws ServletException, IOException { - - String query = "{\"query\":{\"match_all\":{}}}"; - HelpServlet servlet = new HelpServlet(PORT); - this.setServlet(servlet); - // test disabled message - String expectedResponse = "offline"; - testrequest(HTTPMETHOD_GET, query, expectedResponse, false); - testrequest(HTTPMETHOD_POST, query, expectedResponse, false); - testrequest(HTTPMETHOD_PUT, query, expectedResponse, false); - testrequest(HTTPMETHOD_DELETE, query, expectedResponse, false); - servlet.setOffline(false); - // initEsTestWebserver(port); - testrequest(HTTPMETHOD_GET, query, HelpServletBase.RESPONSE_GET, true); - testrequest(HTTPMETHOD_POST, query, HelpServletBase.RESPONSE_POST, true); - testrequest(HTTPMETHOD_PUT, query, HelpServletBase.RESPONSE_PUT, true); - testrequest(HTTPMETHOD_DELETE, query, HelpServletBase.RESPONSE_DELETE, true); - testrequest(HTTPMETHOD_OPTIONS, query, "", false); - // stopTestWebserver(); - } - @Before - public void init() throws IOException{ - HelpServletBase.initEsTestWebserver(PORT); - } - @After - public void deinit() { - HelpServletBase.stopTestWebserver(); - } + private static final int PORT = 40003; + + public TestBaseServlet() { + super("/base", PORT); + } + + @Test + public void test() throws ServletException, IOException { + + String query = "{\"query\":{\"match_all\":{}}}"; + HelpServlet servlet = new HelpServlet(PORT); + this.setServlet(servlet); + // test disabled message + String expectedResponse = "offline"; + testrequest(HTTPMETHOD_GET, query, expectedResponse, false); + testrequest(HTTPMETHOD_POST, query, expectedResponse, false); + testrequest(HTTPMETHOD_PUT, query, expectedResponse, false); + testrequest(HTTPMETHOD_DELETE, query, expectedResponse, false); + servlet.setOffline(false); + // initEsTestWebserver(port); + testrequest(HTTPMETHOD_GET, query, HelpServletBase.RESPONSE_GET, true); + testrequest(HTTPMETHOD_POST, query, HelpServletBase.RESPONSE_POST, true); + testrequest(HTTPMETHOD_PUT, query, HelpServletBase.RESPONSE_PUT, true); + testrequest(HTTPMETHOD_DELETE, query, HelpServletBase.RESPONSE_DELETE, true); + testrequest(HTTPMETHOD_OPTIONS, query, "", false); + // stopTestWebserver(); + } + + @Before + public void init() throws IOException { + HelpServletBase.initEsTestWebserver(PORT); + } + + @After + public void deinit() { + HelpServletBase.stopTestWebserver(); + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java index 3b19f5c4b..415620415 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestConfig.java @@ -44,218 +44,222 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo.Protocol; public class TestConfig { - private static final String TESTFILENAME = "test.properties"; - private static final String TESTKEY1 = "abc"; - private static final String TESTKEY2 = "def"; - private static final String TESTKEY3 = "hhh"; - private static final String TESTKEY4 = "hhv"; - - private static final int TESTVALUE1=123; - private static final int TESTVALUE1_2=1234; - private static final boolean TESTVALUE2 = true; - private static final String TESTVALUE3 = "http://localhost:2223"; - private static final String TESTVALUE4 = "httasdasdas"; - private static final String TESTCONTENT1 = " [test]\n" + - TESTKEY1+"="+TESTVALUE1+"\n" + - "#her a comment\n"+ - TESTKEY2+"="+TESTVALUE2+"\n" + - TESTKEY3+"="+TESTVALUE3; - - - - - @After - @Before - public void init() { - File f=new File(TESTFILENAME); - if(f.exists()) { - f.delete(); - } - } - - public void write(String filename,String lines) { - - try { - Files.write(new File(filename).toPath(), lines.getBytes()); - } catch (IOException e) { - fail("problem writing file "+filename); - } - } - @Test - public void testRead() { - this.write(TESTFILENAME, TESTCONTENT1); - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - Section section = confiuration.getSection("test").get(); - assertNotNull(section); - try { - assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); - assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); - assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); - } catch (ConversionException e) { - fail(e.getMessage()); - } - this.init(); - } - @Test - public void testWrite() { - final String SECTIONNAME = "test"; - //write values - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - Section section=confiuration.addSection(SECTIONNAME); - - section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); - section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); - section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); - confiuration.save(); - - //verify written - ConfigurationFileRepresentation confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - - section = confiuration2.getSection(SECTIONNAME).get(); - assertNotNull(section); - try { - assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); - assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); - assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); - } catch (ConversionException e) { - fail(e.getMessage()); - } - this.init(); - - //write directly into base - confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - section=confiuration.addSection(SECTIONNAME); - confiuration.setProperty(SECTIONNAME,TESTKEY1 , TESTVALUE1); - confiuration.setProperty(SECTIONNAME,TESTKEY2 , TESTVALUE2); - confiuration.setProperty(SECTIONNAME,TESTKEY3 , TESTVALUE3); - confiuration.save(); - - //verify - confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - section = confiuration2.getSection(SECTIONNAME).get(); - assertNotNull(section); - assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME,TESTKEY1).get().intValue()); - assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME,TESTKEY2)); - assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME,TESTKEY3)); - this.init(); - - - } - @Test - public void testOverwrite() { - final String SECTIONNAME = "test"; - //write values - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - Section section=confiuration.addSection(SECTIONNAME); - - section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); - section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); - section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); - confiuration.save(); - - //verify written - ConfigurationFileRepresentation confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - - section = confiuration2.getSection(SECTIONNAME).get(); - - assertNotNull(section); - try { - assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); - assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); - assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); - } catch (ConversionException e) { - fail(e.getMessage()); - } - - //write directly into base - confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - section=confiuration.addSection(SECTIONNAME); - confiuration.setPropertyIfNotAvailable(SECTIONNAME,TESTKEY1 , TESTVALUE1_2); - confiuration.setPropertyIfNotAvailable(SECTIONNAME,TESTKEY4 , TESTVALUE4); - - confiuration.save(); - - //verify - confiuration2=new ConfigurationFileRepresentation(TESTFILENAME); - section = confiuration2.getSection(SECTIONNAME).get(); - assertNotNull(section); - assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME,TESTKEY1).get().intValue()); - assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME,TESTKEY2)); - assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME,TESTKEY3)); - assertEquals(TESTVALUE4, confiuration.getProperty(SECTIONNAME,TESTKEY4)); - this.init(); - - - } - static boolean changeFlag=false; - @Test - public void testChangeListener() { - - changeFlag=false; - this.init(); - ConfigurationFileRepresentation confiuration=new ConfigurationFileRepresentation(TESTFILENAME); - IConfigChangedListener listener = new IConfigChangedListener() { - - @Override - public void onConfigChanged() { - changeFlag=true; - } - }; - confiuration.registerConfigChangedListener(listener ); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - this.write(TESTFILENAME, TESTCONTENT1); - int i=10; - while(i-->0) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - if(changeFlag) { - break; - } - } - confiuration.unregisterConfigChangedListener(listener); - assertTrue("changelistener not called",changeFlag); - } - @Test - public void testHostInfo() { - HostInfo hi=HostInfo.getDefault(); - try { - new URL(hi.toUrl()); - } catch (MalformedURLException e) { - fail("url conversion failed: "+e.getMessage()); - } - hi = new HostInfo("localhost", 44444, Protocol.getValueOf("https")); - try { - new URL(hi.toUrl()); - } catch (MalformedURLException e) { - fail("url conversion failed: "+e.getMessage()); - } - - } - @Test - public void testEnvPropert() { - final String KEY = "basada"; - Section section = new Section("test"); - section.addLine(KEY+"=${USER} in ${HOME}"); - section.parseLines(); - assertTrue(section.getProperty(KEY).length()>" in ".length()); - } - public static void setEnv(String key, String value) { - try { - Map<String, String> env = System.getenv(); - Class<?> cl = env.getClass(); - Field field = cl.getDeclaredField("m"); - field.setAccessible(true); - Map<String, String> writableEnv = (Map<String, String>) field.get(env); - writableEnv.put(key, value); - } catch (Exception e) { - throw new IllegalStateException("Failed to set environment variable", e); - } - } + private static final String TESTFILENAME = "test.properties"; + private static final String TESTKEY1 = "abc"; + private static final String TESTKEY2 = "def"; + private static final String TESTKEY3 = "hhh"; + private static final String TESTKEY4 = "hhv"; + + private static final int TESTVALUE1 = 123; + private static final int TESTVALUE1_2 = 1234; + private static final boolean TESTVALUE2 = true; + private static final String TESTVALUE3 = "http://localhost:2223"; + private static final String TESTVALUE4 = "httasdasdas"; + private static final String TESTCONTENT1 = " [test]\n" + TESTKEY1 + "=" + TESTVALUE1 + "\n" + "#her a comment\n" + + TESTKEY2 + "=" + TESTVALUE2 + "\n" + TESTKEY3 + "=" + TESTVALUE3; + + + + @After + @Before + public void init() { + File f = new File(TESTFILENAME); + if (f.exists()) { + f.delete(); + } + } + + public void write(String filename, String lines) { + + try { + Files.write(new File(filename).toPath(), lines.getBytes()); + } catch (IOException e) { + fail("problem writing file " + filename); + } + } + + @Test + public void testRead() { + this.write(TESTFILENAME, TESTCONTENT1); + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.getSection("test").get(); + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + this.init(); + } + + @Test + public void testWrite() { + final String SECTIONNAME = "test"; + //write values + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.addSection(SECTIONNAME); + + section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); + section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); + section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); + confiuration.save(); + + //verify written + ConfigurationFileRepresentation confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + this.init(); + + //write directly into base + confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration.addSection(SECTIONNAME); + confiuration.setProperty(SECTIONNAME, TESTKEY1, TESTVALUE1); + confiuration.setProperty(SECTIONNAME, TESTKEY2, TESTVALUE2); + confiuration.setProperty(SECTIONNAME, TESTKEY3, TESTVALUE3); + confiuration.save(); + + //verify + confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME, TESTKEY1).get().intValue()); + assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME, TESTKEY2)); + assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME, TESTKEY3)); + this.init(); + + + } + + @Test + public void testOverwrite() { + final String SECTIONNAME = "test"; + //write values + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + Section section = confiuration.addSection(SECTIONNAME); + + section.setProperty(TESTKEY1, String.valueOf(TESTVALUE1)); + section.setProperty(TESTKEY2, String.valueOf(TESTVALUE2)); + section.setProperty(TESTKEY3, String.valueOf(TESTVALUE3)); + confiuration.save(); + + //verify written + ConfigurationFileRepresentation confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + + section = confiuration2.getSection(SECTIONNAME).get(); + + assertNotNull(section); + try { + assertEquals(TESTVALUE1, section.getInt(TESTKEY1, 0)); + assertEquals(TESTVALUE2, section.getBoolean(TESTKEY2, !TESTVALUE2)); + assertEquals(TESTVALUE3, section.getString(TESTKEY3, "")); + } catch (ConversionException e) { + fail(e.getMessage()); + } + + //write directly into base + confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration.addSection(SECTIONNAME); + confiuration.setPropertyIfNotAvailable(SECTIONNAME, TESTKEY1, TESTVALUE1_2); + confiuration.setPropertyIfNotAvailable(SECTIONNAME, TESTKEY4, TESTVALUE4); + + confiuration.save(); + + //verify + confiuration2 = new ConfigurationFileRepresentation(TESTFILENAME); + section = confiuration2.getSection(SECTIONNAME).get(); + assertNotNull(section); + assertEquals(TESTVALUE1, confiuration.getPropertyLong(SECTIONNAME, TESTKEY1).get().intValue()); + assertEquals(TESTVALUE2, confiuration.getPropertyBoolean(SECTIONNAME, TESTKEY2)); + assertEquals(TESTVALUE3, confiuration.getProperty(SECTIONNAME, TESTKEY3)); + assertEquals(TESTVALUE4, confiuration.getProperty(SECTIONNAME, TESTKEY4)); + this.init(); + + + } + + static boolean changeFlag = false; + + @Test + public void testChangeListener() { + + changeFlag = false; + this.init(); + ConfigurationFileRepresentation confiuration = new ConfigurationFileRepresentation(TESTFILENAME); + IConfigChangedListener listener = new IConfigChangedListener() { + + @Override + public void onConfigChanged() { + changeFlag = true; + } + }; + confiuration.registerConfigChangedListener(listener); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + this.write(TESTFILENAME, TESTCONTENT1); + int i = 10; + while (i-- > 0) { + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + if (changeFlag) { + break; + } + } + confiuration.unregisterConfigChangedListener(listener); + assertTrue("changelistener not called", changeFlag); + } + + @Test + public void testHostInfo() { + HostInfo hi = HostInfo.getDefault(); + try { + new URL(hi.toUrl()); + } catch (MalformedURLException e) { + fail("url conversion failed: " + e.getMessage()); + } + hi = new HostInfo("localhost", 44444, Protocol.getValueOf("https")); + try { + new URL(hi.toUrl()); + } catch (MalformedURLException e) { + fail("url conversion failed: " + e.getMessage()); + } + + } + + @Test + public void testEnvPropert() { + final String KEY = "basada"; + Section section = new Section("test"); + section.addLine(KEY + "=${USER} in ${HOME}"); + section.parseLines(); + assertTrue(section.getProperty(KEY).length() > " in ".length()); + } + + public static void setEnv(String key, String value) { + try { + Map<String, String> env = System.getenv(); + Class<?> cl = env.getClass(); + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Map<String, String> writableEnv = (Map<String, String>) field.get(env); + writableEnv.put(key, value); + } catch (Exception e) { + throw new IllegalStateException("Failed to set environment variable", e); + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java index fc244f6b6..4d7cbdce9 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDatabaseFilterConversion.java @@ -32,54 +32,60 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.data.DbFilter; public class TestDatabaseFilterConversion { - @Test - public void testStartsWith() { - String re=DbFilter.createDatabaseRegex("abc*"); - assertEquals("abc.*", re); - } - @Test - public void testEndsWith() { - String re=DbFilter.createDatabaseRegex("*abc"); - assertEquals(".*abc", re); - } - @Test - public void testMultiple() { - String re=DbFilter.createDatabaseRegex("abc*ff*fa"); - assertEquals("abc.*ff.*fa", re); - } - - @Test - public void testPlaceholder() { - String re=DbFilter.createDatabaseRegex("abc?ef"); - assertEquals("abc.{1,1}ef", re); - } - @Test - public void testCombined() { - String re=DbFilter.createDatabaseRegex("abc?ff*fa"); - assertEquals("abc.{1,1}ff.*fa", re); - } - @Test - public void testFilterCheck() { - assertTrue(DbFilter.hasSearchParams("abc?")); - assertTrue(DbFilter.hasSearchParams("bac*")); - assertFalse(DbFilter.hasSearchParams("abc+")); - } - @Test - public void testRangeConversion() { - try { - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gte\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", ">=2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gt\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", ">2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lte\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", "<=2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lt\":2230,\"boost\":2}}}}", - DbFilter.getRangeQuery("port", "<2230").toJSON(),true); - JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"timestamp\":{\"lt\":\"2018-01-01T23:59:59.0Z\",\"boost\":2}}}}", - DbFilter.getRangeQuery("timestamp", "<2018-01-01T23:59:59.0Z").toJSON(),true); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - + @Test + public void testStartsWith() { + String re = DbFilter.createDatabaseRegex("abc*"); + assertEquals("abc.*", re); + } + + @Test + public void testEndsWith() { + String re = DbFilter.createDatabaseRegex("*abc"); + assertEquals(".*abc", re); + } + + @Test + public void testMultiple() { + String re = DbFilter.createDatabaseRegex("abc*ff*fa"); + assertEquals("abc.*ff.*fa", re); + } + + @Test + public void testPlaceholder() { + String re = DbFilter.createDatabaseRegex("abc?ef"); + assertEquals("abc.{1,1}ef", re); + } + + @Test + public void testCombined() { + String re = DbFilter.createDatabaseRegex("abc?ff*fa"); + assertEquals("abc.{1,1}ff.*fa", re); + } + + @Test + public void testFilterCheck() { + assertTrue(DbFilter.hasSearchParams("abc?")); + assertTrue(DbFilter.hasSearchParams("bac*")); + assertFalse(DbFilter.hasSearchParams("abc+")); + } + + @Test + public void testRangeConversion() { + try { + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gte\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", ">=2230").toJSON(), true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"gt\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", ">2230").toJSON(), true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lte\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", "<=2230").toJSON(), true); + JSONAssert.assertEquals("", "{\"query\":{\"range\":{\"port\":{\"lt\":2230,\"boost\":2}}}}", + DbFilter.getRangeQuery("port", "<2230").toJSON(), true); + JSONAssert.assertEquals("", + "{\"query\":{\"range\":{\"timestamp\":{\"lt\":\"2018-01-01T23:59:59.0Z\",\"boost\":2}}}}", + DbFilter.getRangeQuery("timestamp", "<2018-01-01T23:59:59.0Z").toJSON(), true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java index 04259b9f6..cf9d93052 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbClient.java @@ -40,154 +40,154 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.requests.GetIndexRequest; public class TestDbClient { - private static HtDatabaseClient dbClient; - private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer - .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; - - @BeforeClass - public static void init() throws Exception { - - dbClient = new HtDatabaseClient(hosts); - dbClient.waitForYellowStatus(20000); - - } - - @Test - public void testCRUD() { - final String IDX = "test23-knmoinsd"; - final String ID = "abcddd"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; - - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - clearIndexData(IDX); - //Create - String esId = dbClient.doWriteRaw(IDX, ID, JSON); - assertEquals("inserted id is wrong", ID, esId); - //Read - SearchResult<SearchHit> result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); - assertEquals("amount of results is wrong", 1, result.getTotal()); - assertEquals("data not valid", JSON, result.getHits().get(0).getSourceAsString()); - //Update - esId = dbClient.doUpdateOrCreate(IDX, ID, JSON2); - assertEquals("update response not successfull", ID, esId); - //check that update with null fails - assertNull("update with id null should not be possible", dbClient.doUpdateOrCreate(IDX, null, JSON2)); - //Verify update - result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); - assertEquals("amount of results is wrong", 1, result.getTotal()); - assertEquals("data not valid", JSON2, result.getHits().get(0).getSourceAsString()); - //test second read - String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() { - - @Override - public void setEsId(String id) { - - } - - @Override - public String getEsId() { - return ID; - } - }); - //test all read - result = dbClient.doReadAllJsonData(IDX); - assertNotNull("all read not working", result); - - assertEquals("read works not as expected", JSON2, resStr); - //Delete - boolean del = dbClient.doRemove(IDX, new IsEsObject() { - - @Override - public void setEsId(String id) { - - } - - @Override - public String getEsId() { - return ID; - } - }); - assertTrue("item not deleted", del); - //Verify - result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); - assertEquals("amount of results is wrong", 0, result.getTotal()); - - } - - /** - * @param iDX - */ - private void clearIndexData(String idx) { - try { - dbClient.deleteByQuery(new DeleteByQueryRequest(idx, true).source(QueryBuilders.matchAllQuery())); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - @Test - public void testCRUD2() { - final String IDX = "test23-knmoins3d"; - final String ID = "abcddd"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - //Create - String esId = dbClient.doWriteRaw(IDX, ID, JSON); - assertEquals("inserted id is wrong", ID, esId); - //Read - SearchResult<SearchHit> result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); - assertEquals("amount of results is wrong", 1, result.getTotal()); - assertEquals("data not valid", JSON, result.getHits().get(0).getSourceAsString()); - QueryBuilder matchQuery = QueryBuilders.matchQuery("_id", ID); - //Update - assertTrue("update response not successfull", dbClient.doUpdate(IDX, JSON2, matchQuery)); - //check that update with null fails - assertNull("update with id null should not be possible", dbClient.doUpdateOrCreate(IDX, null, JSON2)); - //Verify update - result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); - assertEquals("amount of results is wrong", 1, result.getTotal()); - assertEquals("data not valid", JSON2, result.getHits().get(0).getSourceAsString()); - //test second read - String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() { - - @Override - public void setEsId(String id) { - - } - - @Override - public String getEsId() { - return ID; - } - }); - //test all read - result = dbClient.doReadAllJsonData(IDX); - assertNotNull("all read not working", result); - - assertEquals("read works not as expected", JSON2, resStr); - //Delete - int del = dbClient.doRemove(IDX, matchQuery); - assertTrue("item not deleted", del > 0); - //Verify - result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); - assertEquals("amount of results is wrong", 0, result.getTotal()); - - } + private static HtDatabaseClient dbClient; + private static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))}; + + @BeforeClass + public static void init() throws Exception { + + dbClient = new HtDatabaseClient(hosts); + dbClient.waitForYellowStatus(20000); + + } + + @Test + public void testCRUD() { + final String IDX = "test23-knmoinsd"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + clearIndexData(IDX); + //Create + String esId = dbClient.doWriteRaw(IDX, ID, JSON); + assertEquals("inserted id is wrong", ID, esId); + //Read + SearchResult<SearchHit> result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong", 1, result.getTotal()); + assertEquals("data not valid", JSON, result.getHits().get(0).getSourceAsString()); + //Update + esId = dbClient.doUpdateOrCreate(IDX, ID, JSON2); + assertEquals("update response not successfull", ID, esId); + //check that update with null fails + assertNull("update with id null should not be possible", dbClient.doUpdateOrCreate(IDX, null, JSON2)); + //Verify update + result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong", 1, result.getTotal()); + assertEquals("data not valid", JSON2, result.getHits().get(0).getSourceAsString()); + //test second read + String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() { + + @Override + public void setEsId(String id) { + + } + + @Override + public String getEsId() { + return ID; + } + }); + //test all read + result = dbClient.doReadAllJsonData(IDX); + assertNotNull("all read not working", result); + + assertEquals("read works not as expected", JSON2, resStr); + //Delete + boolean del = dbClient.doRemove(IDX, new IsEsObject() { + + @Override + public void setEsId(String id) { + + } + + @Override + public String getEsId() { + return ID; + } + }); + assertTrue("item not deleted", del); + //Verify + result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong", 0, result.getTotal()); + + } + + /** + * @param iDX + */ + private void clearIndexData(String idx) { + try { + dbClient.deleteByQuery(new DeleteByQueryRequest(idx, true).source(QueryBuilders.matchAllQuery())); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + @Test + public void testCRUD2() { + final String IDX = "test23-knmoins3d"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + //Create + String esId = dbClient.doWriteRaw(IDX, ID, JSON); + assertEquals("inserted id is wrong", ID, esId); + //Read + SearchResult<SearchHit> result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong", 1, result.getTotal()); + assertEquals("data not valid", JSON, result.getHits().get(0).getSourceAsString()); + QueryBuilder matchQuery = QueryBuilders.matchQuery("_id", ID); + //Update + assertTrue("update response not successfull", dbClient.doUpdate(IDX, JSON2, matchQuery)); + //check that update with null fails + assertNull("update with id null should not be possible", dbClient.doUpdateOrCreate(IDX, null, JSON2)); + //Verify update + result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong", 1, result.getTotal()); + assertEquals("data not valid", JSON2, result.getHits().get(0).getSourceAsString()); + //test second read + String resStr = dbClient.doReadJsonData(IDX, new IsEsObject() { + + @Override + public void setEsId(String id) { + + } + + @Override + public String getEsId() { + return ID; + } + }); + //test all read + result = dbClient.doReadAllJsonData(IDX); + assertNotNull("all read not working", result); + + assertEquals("read works not as expected", JSON2, resStr); + //Delete + int del = dbClient.doRemove(IDX, matchQuery); + assertTrue("item not deleted", del > 0); + //Verify + result = dbClient.doReadByQueryJsonData(IDX, QueryBuilders.matchQuery("_id", ID)); + assertEquals("amount of results is wrong", 0, result.getTotal()); + + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java index 93d4b1af6..127908c08 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbQueries.java @@ -35,252 +35,167 @@ import org.onap.ccsdk.features.sdnr.wt.common.test.JSONAssert; public class TestDbQueries { - private static final String MATCH_ALL_QUERY = "{\n" + - " \"query\": {\n" + - " \"match_all\" : {\n" + - " }\n" + - " }\n" + - "}"; - private static final String MATCH_QUERY_KEY = "is-required"; - private static final Object MATCH_QUERY_VALUE = true; - private static final String MATCH_QUERY = "{\n" + - " \"query\": {\n" + - " \"match\" : {\n" + - " \""+MATCH_QUERY_KEY+"\" : "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " }\n" + - "}"; - private static final String MATCH_QUERY_KEY2 = "node-id"; - private static final Object MATCH_QUERY_VALUE2 = "sim2"; - private static final String BOOL_QUERY_MUST = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"must\": [\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " },\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY2+"\":"+MATCH_QUERY_VALUE2+" \n" + - " }\n" + - " }\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - private static final String BOOL_QUERY_MUST_SINGLE = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"must\": {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final String BOOL_QUERY_SHOULD = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"should\": [\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " },\n" + - " {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY2+"\":"+MATCH_QUERY_VALUE2+" \n" + - " }\n" + - " }\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - private static final String BOOL_QUERY_SHOULD_SINGLE = "{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"should\": {\n" + - " \"match\": {\n" + - " \""+MATCH_QUERY_KEY+"\": "+MATCH_QUERY_VALUE+"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final String RANGE_QUERY_KEY = "timestamp"; - private static final String RANGE_QUERY_LTEND = "2017-08-10T20:00:00.0Z"; - private static final String RANGE_QUERY = "{\n" + - " \"query\": {\n" + - " \"range\" : {\n" + - " \""+RANGE_QUERY_KEY+"\" : {\n" + - " \"lte\" : \""+RANGE_QUERY_LTEND+"\",\n" + - " \"boost\": 2.0\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final String RANGEBOOL_QUERY="{\n" + - " \"query\": {\n" + - " \"bool\": {\n" + - " \"must\": [\n" + - " {\n" + - " \"match\": {\n" + - " \"is-required\": true\n" + - " }\n" + - " },\n" + - " {\n" + - " \"regexp\": {\n" + - " \"node-id\": {\n" + - " \"max_determinized_states\": 10000,\n" + - " \"flags\": \"ALL\",\n" + - " \"value\": \"sim.*\"\n" + - " }\n" + - " }\n" + - " }\n" + - " ]\n" + - " }\n" + - " }\n" + - "}"; - private static final String AGG_FIELD = "severity"; - private static final String AGG_QUERY = "{\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"aggs\": {\n" + - " \"severity\": {\n" + - " \"terms\": {\n" + - " \"field\": \""+AGG_FIELD+"\"\n" + - " }\n" + - " }\n" + - " }\n" + - "}"; - private static final long FROMANDSIZE_QUERY_SIZE = 20; - private static final long FROMANDSIZE_QUERY_FROM = 120; - private static final String FROMANDSIZE_QUERY = "{\n" + - " \"size\": "+FROMANDSIZE_QUERY_SIZE+",\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"from\":"+FROMANDSIZE_QUERY_FROM+"\n" + - "}"; - private static final String TERMQUERY_KEY = "node-id"; - private static final String TERMQUERY_VALUE = "abc"; - private static final String TERM_QUERY = "{\n" + - " \"query\": {\n" + - " \"term\": {\n" + - " \""+TERMQUERY_KEY+"\": \""+TERMQUERY_VALUE+"\"\n" + - " }\n" + - " }\n" + - "}"; - private static final String SORTING_PROPERTY = "node-id"; - private static final String SORTING_QUERY_ASC = "{\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"sort\": [\n" + - " {\n" + - " \""+SORTING_PROPERTY+"\": {\n" + - " \"order\": \"asc\"\n" + - " }\n" + - " }\n" + - " ]\n" + - "}"; - private static final String SORTING_QUERY_DESC = "{\n" + - " \"query\": {\n" + - " \"match_all\": {}\n" + - " },\n" + - " \"sort\": [\n" + - " {\n" + - " \""+SORTING_PROPERTY+"\": {\n" + - " \"order\": \"desc\"\n" + - " }\n" + - " }\n" + - " ]\n" + - "}"; - - private void testEquals(String message,String json, QueryBuilder query) { - this.testEquals(message, json, query,true); - } - private void testEquals(String message,String json, QueryBuilder query,boolean strict) { - - try { - System.out.println("===test if "+message+"==================="); - System.out.println("orig : "+trim(json)); - System.out.println("totest: "+query.toJSON().trim()); - JSONAssert.assertEquals(json,query.toJSON(),strict); - } catch (JSONException e) { - fail(message); - } - } - - private String trim(String json) { - return json.trim().replaceAll("\n","").replaceAll(" ", ""); - } + private static final String MATCH_ALL_QUERY = + "{\n" + " \"query\": {\n" + " \"match_all\" : {\n" + " }\n" + " }\n" + "}"; + private static final String MATCH_QUERY_KEY = "is-required"; + private static final Object MATCH_QUERY_VALUE = true; + private static final String MATCH_QUERY = "{\n" + " \"query\": {\n" + " \"match\" : {\n" + + " \"" + MATCH_QUERY_KEY + "\" : " + MATCH_QUERY_VALUE + "\n" + " }\n" + " }\n" + "}"; + private static final String MATCH_QUERY_KEY2 = "node-id"; + private static final Object MATCH_QUERY_VALUE2 = "sim2"; + private static final String BOOL_QUERY_MUST = + "{\n" + " \"query\": {\n" + " \"bool\": {\n" + " \"must\": [\n" + " {\n" + + " \"match\": {\n" + " \"" + MATCH_QUERY_KEY + "\": " + + MATCH_QUERY_VALUE + "\n" + " }\n" + " },\n" + + " {\n" + " \"match\": {\n" + " \"" + + MATCH_QUERY_KEY2 + "\":" + MATCH_QUERY_VALUE2 + " \n" + " }\n" + + " }\n" + " ]\n" + " }\n" + " }\n" + "}"; + private static final String BOOL_QUERY_MUST_SINGLE = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"must\": {\n" + " \"match\": {\n" + " \"" + + MATCH_QUERY_KEY + "\": " + MATCH_QUERY_VALUE + "\n" + " }\n" + " }\n" + + " }\n" + " }\n" + "}"; + private static final String BOOL_QUERY_SHOULD = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"should\": [\n" + " {\n" + " \"match\": {\n" + + " \"" + MATCH_QUERY_KEY + "\": " + MATCH_QUERY_VALUE + "\n" + + " }\n" + " },\n" + " {\n" + + " \"match\": {\n" + " \"" + MATCH_QUERY_KEY2 + "\":" + + MATCH_QUERY_VALUE2 + " \n" + " }\n" + " }\n" + " ]\n" + + " }\n" + " }\n" + "}"; + private static final String BOOL_QUERY_SHOULD_SINGLE = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"should\": {\n" + " \"match\": {\n" + " \"" + + MATCH_QUERY_KEY + "\": " + MATCH_QUERY_VALUE + "\n" + " }\n" + " }\n" + + " }\n" + " }\n" + "}"; + private static final String RANGE_QUERY_KEY = "timestamp"; + private static final String RANGE_QUERY_LTEND = "2017-08-10T20:00:00.0Z"; + private static final String RANGE_QUERY = "{\n" + " \"query\": {\n" + " \"range\" : {\n" + + " \"" + RANGE_QUERY_KEY + "\" : {\n" + " \"lte\" : \"" + RANGE_QUERY_LTEND + + "\",\n" + " \"boost\": 2.0\n" + " }\n" + " }\n" + " }\n" + "}"; + private static final String RANGEBOOL_QUERY = "{\n" + " \"query\": {\n" + " \"bool\": {\n" + + " \"must\": [\n" + " {\n" + " \"match\": {\n" + + " \"is-required\": true\n" + " }\n" + " },\n" + + " {\n" + " \"regexp\": {\n" + " \"node-id\": {\n" + + " \"max_determinized_states\": 10000,\n" + + " \"flags\": \"ALL\",\n" + " \"value\": \"sim.*\"\n" + + " }\n" + " }\n" + " }\n" + " ]\n" + + " }\n" + " }\n" + "}"; + private static final String AGG_FIELD = "severity"; + private static final String AGG_QUERY = + "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"aggs\": {\n" + + " \"severity\": {\n" + " \"terms\": {\n" + " \"field\": \"" + + AGG_FIELD + "\"\n" + " }\n" + " }\n" + " }\n" + "}"; + private static final long FROMANDSIZE_QUERY_SIZE = 20; + private static final long FROMANDSIZE_QUERY_FROM = 120; + private static final String FROMANDSIZE_QUERY = "{\n" + " \"size\": " + FROMANDSIZE_QUERY_SIZE + ",\n" + + " \"query\": {\n" + " \"match_all\": {}\n" + " },\n" + " \"from\":" + + FROMANDSIZE_QUERY_FROM + "\n" + "}"; + private static final String TERMQUERY_KEY = "node-id"; + private static final String TERMQUERY_VALUE = "abc"; + private static final String TERM_QUERY = "{\n" + " \"query\": {\n" + " \"term\": {\n" + " \"" + + TERMQUERY_KEY + "\": \"" + TERMQUERY_VALUE + "\"\n" + " }\n" + " }\n" + "}"; + private static final String SORTING_PROPERTY = "node-id"; + private static final String SORTING_QUERY_ASC = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + + " },\n" + " \"sort\": [\n" + " {\n" + " \"" + SORTING_PROPERTY + "\": {\n" + + " \"order\": \"asc\"\n" + " }\n" + " }\n" + " ]\n" + "}"; + private static final String SORTING_QUERY_DESC = "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + + " },\n" + " \"sort\": [\n" + " {\n" + " \"" + SORTING_PROPERTY + "\": {\n" + + " \"order\": \"desc\"\n" + " }\n" + " }\n" + " ]\n" + "}"; - @Test - public void testMatchAll() { - testEquals("match all query is wrong", MATCH_ALL_QUERY, QueryBuilders.matchAllQuery()); - } - @Test - public void testMatch() { - testEquals("match query is wrong", MATCH_QUERY, QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)); - } - @Test - public void testBoolMust() { - testEquals("bool query is wrong", BOOL_QUERY_MUST, - QueryBuilders.boolQuery(). - must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)). - must(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); - } - @Test - public void testBoolMustSingle() { - testEquals("bool single query is wrong", BOOL_QUERY_MUST_SINGLE, - QueryBuilders.boolQuery(). - must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); - } - @Test - public void testBoolShould() { - testEquals("bool query is wrong", BOOL_QUERY_SHOULD, - QueryBuilders.boolQuery(). - should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)). - should(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); - } - @Test - public void testBoolShouldSingle() { - testEquals("bool single query is wrong", BOOL_QUERY_SHOULD_SINGLE, - QueryBuilders.boolQuery(). - should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); - } - @Test - public void testRange() { - testEquals("range query is wrong", RANGE_QUERY, QueryBuilders.rangeQuery(RANGE_QUERY_KEY).lte(RANGE_QUERY_LTEND)); - - } - @Test - public void testAggregation() { - testEquals("aggregation query is wrong",AGG_QUERY, QueryBuilders.matchAllQuery().aggregations(AGG_FIELD)); - } - @Test - public void testSizeAndFrom() { - testEquals("aggregation query is wrong",FROMANDSIZE_QUERY, QueryBuilders.matchAllQuery().size(FROMANDSIZE_QUERY_SIZE).from(FROMANDSIZE_QUERY_FROM)); - } - @Test - public void testRegex() { - testEquals("range and bool query is wrong1",RANGEBOOL_QUERY,QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("is-required", true)).must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))),false); - BoolQueryBuilder q = QueryBuilders.boolQuery().must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))); - q.must(QueryBuilders.matchQuery("is-required", true)); - testEquals("range and bool query is wrong2",RANGEBOOL_QUERY,q,false); - } - @Test - public void testTerm() { - testEquals("term query is wrong", TERM_QUERY, QueryBuilders.termQuery(TERMQUERY_KEY, TERMQUERY_VALUE)); - } - @Test - public void testSorting() { - testEquals("sortorder is wrong",SORTING_QUERY_ASC, QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.ASCENDING)); - testEquals("sortorder is wrong",SORTING_QUERY_DESC, QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.DESCENDING)); - } + private void testEquals(String message, String json, QueryBuilder query) { + this.testEquals(message, json, query, true); + } + + private void testEquals(String message, String json, QueryBuilder query, boolean strict) { + + try { + System.out.println("===test if " + message + "==================="); + System.out.println("orig : " + trim(json)); + System.out.println("totest: " + query.toJSON().trim()); + JSONAssert.assertEquals(json, query.toJSON(), strict); + } catch (JSONException e) { + fail(message); + } + } + + private String trim(String json) { + return json.trim().replaceAll("\n", "").replaceAll(" ", ""); + } + + @Test + public void testMatchAll() { + testEquals("match all query is wrong", MATCH_ALL_QUERY, QueryBuilders.matchAllQuery()); + } + + @Test + public void testMatch() { + testEquals("match query is wrong", MATCH_QUERY, QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)); + } + + @Test + public void testBoolMust() { + testEquals("bool query is wrong", BOOL_QUERY_MUST, + QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)) + .must(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); + } + + @Test + public void testBoolMustSingle() { + testEquals("bool single query is wrong", BOOL_QUERY_MUST_SINGLE, + QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); + } + + @Test + public void testBoolShould() { + testEquals("bool query is wrong", BOOL_QUERY_SHOULD, + QueryBuilders.boolQuery().should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE)) + .should(QueryBuilders.matchQuery(MATCH_QUERY_KEY2, MATCH_QUERY_VALUE2))); + } + + @Test + public void testBoolShouldSingle() { + testEquals("bool single query is wrong", BOOL_QUERY_SHOULD_SINGLE, + QueryBuilders.boolQuery().should(QueryBuilders.matchQuery(MATCH_QUERY_KEY, MATCH_QUERY_VALUE))); + } + + @Test + public void testRange() { + testEquals("range query is wrong", RANGE_QUERY, + QueryBuilders.rangeQuery(RANGE_QUERY_KEY).lte(RANGE_QUERY_LTEND)); + + } + + @Test + public void testAggregation() { + testEquals("aggregation query is wrong", AGG_QUERY, QueryBuilders.matchAllQuery().aggregations(AGG_FIELD)); + } + + @Test + public void testSizeAndFrom() { + testEquals("aggregation query is wrong", FROMANDSIZE_QUERY, + QueryBuilders.matchAllQuery().size(FROMANDSIZE_QUERY_SIZE).from(FROMANDSIZE_QUERY_FROM)); + } + + @Test + public void testRegex() { + testEquals("range and bool query is wrong1", RANGEBOOL_QUERY, + QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("is-required", true)) + .must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))), + false); + BoolQueryBuilder q = + QueryBuilders.boolQuery().must(QueryBuilders.regex("node-id", DbFilter.createDatabaseRegex("sim*"))); + q.must(QueryBuilders.matchQuery("is-required", true)); + testEquals("range and bool query is wrong2", RANGEBOOL_QUERY, q, false); + } + + @Test + public void testTerm() { + testEquals("term query is wrong", TERM_QUERY, QueryBuilders.termQuery(TERMQUERY_KEY, TERMQUERY_VALUE)); + } + + @Test + public void testSorting() { + testEquals("sortorder is wrong", SORTING_QUERY_ASC, + QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.ASCENDING)); + testEquals("sortorder is wrong", SORTING_QUERY_DESC, + QueryBuilders.matchAllQuery().sort(SORTING_PROPERTY, SortOrder.DESCENDING)); + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java index 2226c5e7e..756d70c85 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestDbRequests.java @@ -73,491 +73,491 @@ import org.json.JSONObject; public class TestDbRequests { - private static HtDatabaseClient dbClient; - private static HostInfo[] hosts = new HostInfo[] { new HostInfo("localhost", Integer - .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200")) }; - - @BeforeClass - public static void init() throws Exception { - - dbClient = new HtDatabaseClient(hosts); - - } - - @AfterClass - public static void deinit() { - if (dbClient != null) { - dbClient.close(); - } - } - - @Test - public void testHealth() { - - ClusterHealthResponse response = null; - ClusterHealthRequest request = new ClusterHealthRequest(); - request.timeout(10); - try { - response = dbClient.health(request); - } catch (UnsupportedOperationException | IOException | JSONException e) { - fail(e.getMessage()); - } - assertNotNull("response is null", response); - assertTrue(response.isStatusMinimal(ClusterHealthResponse.HEALTHSTATUS_YELLOW)); - } - - @Test - public void testCount() { - - } - - @Test - public void testIndexAndAliasList() { - final String ALIAS = "asdoi32kmsasd"; - final String IDX = ALIAS + "-v1"; - CreateIndexRequest request = new CreateIndexRequest(IDX); - CreateIndexResponse response = null; - try { - response = dbClient.createIndex(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - - CreateAliasRequest request3 = new CreateAliasRequest(IDX, ALIAS); - CreateAliasResponse response3 = null; - try { - response3 = dbClient.createAlias(request3); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response3); - assertTrue(response3.isResponseSucceeded()); - - assertTrue("index not existing", dbClient.isExistsIndex(IDX)); - ListIndicesResponse response2 = null; - try { - response2 = dbClient.getIndices(); - } catch (ParseException | IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertNotNull(response2.getEntries()); - assertTrue(response2.getEntries().size() > 0); - - DeleteIndexRequest request11 = new DeleteIndexRequest(IDX); - - DeleteIndexResponse response11 = null; - try { - response11 = dbClient.deleteIndex(request11); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response11); - assertFalse("index still existing", dbClient.isExistsIndex(IDX)); - this.deleteAlias(IDX, ALIAS); - this.deleteIndex(IDX); - } - - @Test - public void testCreateAndDeleteIndex() { - final String IDX = "testcidx1"; - CreateIndexRequest request = new CreateIndexRequest(IDX); - CreateIndexResponse response = null; - try { - response = dbClient.createIndex(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - - assertTrue("index not existing", dbClient.isExistsIndex(IDX)); - - DeleteIndexRequest request2 = new DeleteIndexRequest(IDX); - - DeleteIndexResponse response2 = null; - try { - response2 = dbClient.deleteIndex(request2); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertFalse("index still existing", dbClient.isExistsIndex(IDX)); - this.deleteIndex(IDX); - } - - @Test - public void testInsertAndDelete() { - final String IDX = "tesnt23-knmoinsd"; - final String ID = "abcddd"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX).mappings(defaultMappings(IDX, false))); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - // delete data - DeleteRequest request2 = new DeleteRequest(IDX, IDX, ID); - DeleteResponse response2 = null; - try { - response2 = dbClient.delete(request2); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertTrue(response2.isDeleted()); - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify data deleted - GetRequest request4 = new GetRequest(IDX, IDX, ID); - GetResponse response4 = null; - try { - response4 = dbClient.get(request4); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response4); - assertFalse("data still existing", response4.isExists()); - this.deleteIndex(IDX); - } - - /** - * @param b - * @return - */ - private JSONObject defaultMappings(String idx, boolean useStrict) { - String mapping = "{}"; - return new JSONObject(String.format("{\"%s\":{%s\"properties\":%s}}", idx, - useStrict ? "\"dynamic\": false," : "\"dynamic\": true,", mapping)); - } - - @Test - public void testInsertAndDeleteByQuery() { - final String IDX = "test534-knmoinsd"; - final String ID = "abcdddseae"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - - // delete data - DeleteByQueryRequest request2 = new DeleteByQueryRequest(IDX); - request2.source(QueryBuilders.matchQuery("_id", ID)); - DeleteByQueryResponse response2 = null; - try { - response2 = dbClient.deleteByQuery(request2); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response2); - assertTrue(response2.isResponseSucceeded()); - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify data deleted - GetRequest request4 = new GetRequest(IDX, IDX, ID); - GetResponse response4 = null; - try { - response4 = dbClient.get(request4); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response4); - assertFalse("data still existing", response4.isExists()); - this.deleteIndex(IDX); - } - - private void insert(String IDX, String ID, String JSON) { - - // create data - IndexRequest request = new IndexRequest(IDX, IDX, ID); - request.source(JSON); - String responseId = null; - responseId = dbClient.doWriteRaw(IDX, ID, JSON); - assertNotNull(responseId); - if (ID != null) { - assertEquals("id not correct", ID, responseId); - } else { - ID = responseId; - } - // do db refresh - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify data exists - String response3 = null; - response3 = dbClient.doReadJsonData(IDX, ID); - assertNotNull(response3); - JSONAssert.assertEquals("could not verify update", JSON, response3, true); - } - - @Test - public void testSearch() { - final String IDX = "testb44-moinsd"; - final String ID = "abe"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String ID2 = "abe2"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; - final String ID3 = "abe3"; - final String JSON3 = "{\"data\":{\"inner\":\"more3\"}}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - this.insert(IDX, ID2, JSON2); - this.insert(IDX, ID3, JSON3); - SearchRequest request = new SearchRequest(IDX, IDX); - request.setQuery(QueryBuilders.matchAllQuery()); - SearchResponse response = null; - try { - response = dbClient.search(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertEquals("not all items found", 3, response.getHits().length); - assertEquals("incorrect index", IDX, response.getHits()[0].getIndex()); - assertEquals("incorrect type", IDX, response.getHits()[0].getType()); - this.deleteIndex(IDX); - } - - @Test - public void testUpdate() { - final String IDX = "test45134-moinsd"; - final String ID = "assbe"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - UpdateRequest request = new UpdateRequest(IDX, IDX, ID); - UpdateResponse response = null; - try { - request.source(new JSONObject(JSON2)); - response = dbClient.update(request); - } catch (JSONException | IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.succeeded()); - // refresh index - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify update - GetRequest request3 = new GetRequest(IDX, IDX, ID); - GetResponse response3 = null; - try { - response3 = dbClient.get(request3); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response3); - JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); - this.deleteIndex(IDX); - } - - @Test - public void testUpdateByQuery() { - final String IDX = "test224534k-moinsd"; - final String ID = "asssabe"; - final String JSON = "{\"data\":{\"inner\":\"more\"}}"; - final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; - try { - if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { - dbClient.createIndex(new CreateIndexRequest(IDX)); - } - } catch (IOException e) { - fail("unable to create index"); - } - this.insert(IDX, ID, JSON); - UpdateByQueryRequest request = new UpdateByQueryRequest(IDX, IDX); - UpdateByQueryResponse response = null; - try { - request.source(ID, new JSONObject(JSON2)); - response = dbClient.update(request); - } catch (JSONException | IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.isUpdated()); - // refresh index - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - // verify update - GetRequest request3 = new GetRequest(IDX, IDX, ID); - GetResponse response3 = null; - try { - response3 = dbClient.get(request3); - } catch (IOException e1) { - fail(e1.getMessage()); - } - assertNotNull(response3); - JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); - this.deleteIndex(IDX); - } - - @Test - public void testAggregations() { - final String IDX = "test3227533677-moisnsd"; - final String JSON = "{ \"node-id\":\"sim1\",\"severity\":\"critical\"}"; - final String JSON2 = "{ \"node-id\":\"sim2\",\"severity\":\"critical\"}"; - final String JSON3 = "{ \"node-id\":\"sim3\",\"severity\":\"minor\"}"; - final String JSON4 = "{ \"node-id\":\"sim4\",\"severity\":\"warning\"}"; - final String JSON5 = "{ \"node-id\":\"sim5\",\"severity\":\"major\"}"; - final String MAPPINGS = String.format("{\"" + IDX + "\":{\"properties\":%s}}", - "{\"node-id\":{\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"}}"); - // create index with mapping keyword - CreateIndexResponse iresponse = null; - try { - if (!dbClient.isExistsIndex(IDX)) { - iresponse = dbClient.createIndex(new CreateIndexRequest(IDX).mappings(new JSONObject(MAPPINGS))); - assertNotNull(iresponse); - assertTrue(iresponse.isAcknowledged()); - } - } catch (IOException e1) { - this.deleteIndex(IDX); - fail("unable to create index: " + e1.getMessage()); - } - - // fill index - this.insert(IDX, null, JSON); - this.insert(IDX, null, JSON2); - this.insert(IDX, null, JSON3); - this.insert(IDX, null, JSON4); - this.insert(IDX, null, JSON5); - // refresh index - try { - dbClient.refreshIndex(new RefreshIndexRequest(IDX)); - } catch (IOException e) { - fail(e.getMessage()); - } - - SearchRequest request = new SearchRequest(IDX, IDX); - request.setQuery(QueryBuilders.matchAllQuery().aggregations("severity").size(0)); - SearchResponse response = null; - try { - response = dbClient.search(request); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(response); - assertTrue(response.hasAggregations()); - assertEquals("aggregation size not correct", 4, response.getAggregations("severity").size()); - - List<String> items1 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 0)); - List<String> items2 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 2)); - assertEquals("pagination does not work", 2, items1.size()); - assertEquals("pagination does not work", 2, items2.size()); - for (String s : items1) { - assertFalse("pagination overlap is not allowed", items2.contains(s)); - } - for (String s : items2) { - assertFalse("pagination overlap is not allowed", items1.contains(s)); - } - - this.deleteIndex(IDX); - } - - @Test - public void testStatistics() { - NodeStatsResponse stats = null; - try { - stats = dbClient.stats(new NodeStatsRequest()); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(stats); - System.out.println(stats.getNodesInfo()); - System.out.println(stats.getNodeStatistics()); - } - - // @Test - public void testPreventAutoCreateIndex() { - final String IDX1 = "acidx1"; - final String ID1 = "acid1"; - final String IDX2 = "acidx2"; - final String ID2 = "acid2"; - final String OBJ = "{\"test\":5}"; - - ClusterSettingsResponse settingsResponse = null; - String esId = null; - // set setting to allow autocreate - try { - settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(settingsResponse); - assertTrue(settingsResponse.isAcknowledged()); - // test if something new can be created - esId = dbClient.doWriteRaw(IDX1, IDX1, ID1, OBJ); - assertEquals(ID1, esId); - // set setting to deny autocreate - try { - settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(false)); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(settingsResponse); - assertTrue(settingsResponse.isAcknowledged()); - // test if something new cannot be created - esId = dbClient.doWriteRaw(IDX2, IDX2, ID2, OBJ); - assertNull(esId); - // set setting to allow autocreate - try { - settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); - } catch (IOException e) { - fail(e.getMessage()); - } - assertNotNull(settingsResponse); - assertTrue(settingsResponse.isAcknowledged()); - - } - - private void deleteAlias(String idx, String alias) { - try { - dbClient.deleteAlias(new DeleteAliasRequest(idx, alias)); - } catch (IOException e) { - - } - } - - private void deleteIndex(String idx) { - try { - dbClient.deleteIndex(new DeleteIndexRequest(idx)); - } catch (IOException e) { - - } - } + private static HtDatabaseClient dbClient; + private static HostInfo[] hosts = new HostInfo[] {new HostInfo("localhost", Integer + .valueOf(System.getProperty("databaseport") != null ? System.getProperty("databaseport") : "49200"))}; + + @BeforeClass + public static void init() throws Exception { + + dbClient = new HtDatabaseClient(hosts); + + } + + @AfterClass + public static void deinit() { + if (dbClient != null) { + dbClient.close(); + } + } + + @Test + public void testHealth() { + + ClusterHealthResponse response = null; + ClusterHealthRequest request = new ClusterHealthRequest(); + request.timeout(10); + try { + response = dbClient.health(request); + } catch (UnsupportedOperationException | IOException | JSONException e) { + fail(e.getMessage()); + } + assertNotNull("response is null", response); + assertTrue(response.isStatusMinimal(ClusterHealthResponse.HEALTHSTATUS_YELLOW)); + } + + @Test + public void testCount() { + + } + + @Test + public void testIndexAndAliasList() { + final String ALIAS = "asdoi32kmsasd"; + final String IDX = ALIAS + "-v1"; + CreateIndexRequest request = new CreateIndexRequest(IDX); + CreateIndexResponse response = null; + try { + response = dbClient.createIndex(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + + CreateAliasRequest request3 = new CreateAliasRequest(IDX, ALIAS); + CreateAliasResponse response3 = null; + try { + response3 = dbClient.createAlias(request3); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response3); + assertTrue(response3.isResponseSucceeded()); + + assertTrue("index not existing", dbClient.isExistsIndex(IDX)); + ListIndicesResponse response2 = null; + try { + response2 = dbClient.getIndices(); + } catch (ParseException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertNotNull(response2.getEntries()); + assertTrue(response2.getEntries().size() > 0); + + DeleteIndexRequest request11 = new DeleteIndexRequest(IDX); + + DeleteIndexResponse response11 = null; + try { + response11 = dbClient.deleteIndex(request11); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response11); + assertFalse("index still existing", dbClient.isExistsIndex(IDX)); + this.deleteAlias(IDX, ALIAS); + this.deleteIndex(IDX); + } + + @Test + public void testCreateAndDeleteIndex() { + final String IDX = "testcidx1"; + CreateIndexRequest request = new CreateIndexRequest(IDX); + CreateIndexResponse response = null; + try { + response = dbClient.createIndex(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + + assertTrue("index not existing", dbClient.isExistsIndex(IDX)); + + DeleteIndexRequest request2 = new DeleteIndexRequest(IDX); + + DeleteIndexResponse response2 = null; + try { + response2 = dbClient.deleteIndex(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertFalse("index still existing", dbClient.isExistsIndex(IDX)); + this.deleteIndex(IDX); + } + + @Test + public void testInsertAndDelete() { + final String IDX = "tesnt23-knmoinsd"; + final String ID = "abcddd"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX).mappings(defaultMappings(IDX, false))); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + // delete data + DeleteRequest request2 = new DeleteRequest(IDX, IDX, ID); + DeleteResponse response2 = null; + try { + response2 = dbClient.delete(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertTrue(response2.isDeleted()); + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data deleted + GetRequest request4 = new GetRequest(IDX, IDX, ID); + GetResponse response4 = null; + try { + response4 = dbClient.get(request4); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response4); + assertFalse("data still existing", response4.isExists()); + this.deleteIndex(IDX); + } + + /** + * @param b + * @return + */ + private JSONObject defaultMappings(String idx, boolean useStrict) { + String mapping = "{}"; + return new JSONObject(String.format("{\"%s\":{%s\"properties\":%s}}", idx, + useStrict ? "\"dynamic\": false," : "\"dynamic\": true,", mapping)); + } + + @Test + public void testInsertAndDeleteByQuery() { + final String IDX = "test534-knmoinsd"; + final String ID = "abcdddseae"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + + // delete data + DeleteByQueryRequest request2 = new DeleteByQueryRequest(IDX); + request2.source(QueryBuilders.matchQuery("_id", ID)); + DeleteByQueryResponse response2 = null; + try { + response2 = dbClient.deleteByQuery(request2); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response2); + assertTrue(response2.isResponseSucceeded()); + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data deleted + GetRequest request4 = new GetRequest(IDX, IDX, ID); + GetResponse response4 = null; + try { + response4 = dbClient.get(request4); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response4); + assertFalse("data still existing", response4.isExists()); + this.deleteIndex(IDX); + } + + private void insert(String IDX, String ID, String JSON) { + + // create data + IndexRequest request = new IndexRequest(IDX, IDX, ID); + request.source(JSON); + String responseId = null; + responseId = dbClient.doWriteRaw(IDX, ID, JSON); + assertNotNull(responseId); + if (ID != null) { + assertEquals("id not correct", ID, responseId); + } else { + ID = responseId; + } + // do db refresh + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify data exists + String response3 = null; + response3 = dbClient.doReadJsonData(IDX, ID); + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON, response3, true); + } + + @Test + public void testSearch() { + final String IDX = "testb44-moinsd"; + final String ID = "abe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String ID2 = "abe2"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"}}"; + final String ID3 = "abe3"; + final String JSON3 = "{\"data\":{\"inner\":\"more3\"}}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + this.insert(IDX, ID2, JSON2); + this.insert(IDX, ID3, JSON3); + SearchRequest request = new SearchRequest(IDX, IDX); + request.setQuery(QueryBuilders.matchAllQuery()); + SearchResponse response = null; + try { + response = dbClient.search(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertEquals("not all items found", 3, response.getHits().length); + assertEquals("incorrect index", IDX, response.getHits()[0].getIndex()); + assertEquals("incorrect type", IDX, response.getHits()[0].getType()); + this.deleteIndex(IDX); + } + + @Test + public void testUpdate() { + final String IDX = "test45134-moinsd"; + final String ID = "assbe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + UpdateRequest request = new UpdateRequest(IDX, IDX, ID); + UpdateResponse response = null; + try { + request.source(new JSONObject(JSON2)); + response = dbClient.update(request); + } catch (JSONException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.succeeded()); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify update + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); + this.deleteIndex(IDX); + } + + @Test + public void testUpdateByQuery() { + final String IDX = "test224534k-moinsd"; + final String ID = "asssabe"; + final String JSON = "{\"data\":{\"inner\":\"more\"}}"; + final String JSON2 = "{\"data\":{\"inner\":\"more2\"},\"data2\":\"value2\",\"data3\":true}"; + try { + if (!dbClient.indicesExists(new GetIndexRequest(IDX))) { + dbClient.createIndex(new CreateIndexRequest(IDX)); + } + } catch (IOException e) { + fail("unable to create index"); + } + this.insert(IDX, ID, JSON); + UpdateByQueryRequest request = new UpdateByQueryRequest(IDX, IDX); + UpdateByQueryResponse response = null; + try { + request.source(ID, new JSONObject(JSON2)); + response = dbClient.update(request); + } catch (JSONException | IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.isUpdated()); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + // verify update + GetRequest request3 = new GetRequest(IDX, IDX, ID); + GetResponse response3 = null; + try { + response3 = dbClient.get(request3); + } catch (IOException e1) { + fail(e1.getMessage()); + } + assertNotNull(response3); + JSONAssert.assertEquals("could not verify update", JSON2, response3.getSourceAsBytesRef(), true); + this.deleteIndex(IDX); + } + + @Test + public void testAggregations() { + final String IDX = "test3227533677-moisnsd"; + final String JSON = "{ \"node-id\":\"sim1\",\"severity\":\"critical\"}"; + final String JSON2 = "{ \"node-id\":\"sim2\",\"severity\":\"critical\"}"; + final String JSON3 = "{ \"node-id\":\"sim3\",\"severity\":\"minor\"}"; + final String JSON4 = "{ \"node-id\":\"sim4\",\"severity\":\"warning\"}"; + final String JSON5 = "{ \"node-id\":\"sim5\",\"severity\":\"major\"}"; + final String MAPPINGS = String.format("{\"" + IDX + "\":{\"properties\":%s}}", + "{\"node-id\":{\"type\": \"keyword\"},\"severity\": {\"type\": \"keyword\"}}"); + // create index with mapping keyword + CreateIndexResponse iresponse = null; + try { + if (!dbClient.isExistsIndex(IDX)) { + iresponse = dbClient.createIndex(new CreateIndexRequest(IDX).mappings(new JSONObject(MAPPINGS))); + assertNotNull(iresponse); + assertTrue(iresponse.isAcknowledged()); + } + } catch (IOException e1) { + this.deleteIndex(IDX); + fail("unable to create index: " + e1.getMessage()); + } + + // fill index + this.insert(IDX, null, JSON); + this.insert(IDX, null, JSON2); + this.insert(IDX, null, JSON3); + this.insert(IDX, null, JSON4); + this.insert(IDX, null, JSON5); + // refresh index + try { + dbClient.refreshIndex(new RefreshIndexRequest(IDX)); + } catch (IOException e) { + fail(e.getMessage()); + } + + SearchRequest request = new SearchRequest(IDX, IDX); + request.setQuery(QueryBuilders.matchAllQuery().aggregations("severity").size(0)); + SearchResponse response = null; + try { + response = dbClient.search(request); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(response); + assertTrue(response.hasAggregations()); + assertEquals("aggregation size not correct", 4, response.getAggregations("severity").size()); + + List<String> items1 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 0)); + List<String> items2 = Arrays.asList(response.getAggregations("severity").getKeysAsPagedStringList(2, 2)); + assertEquals("pagination does not work", 2, items1.size()); + assertEquals("pagination does not work", 2, items2.size()); + for (String s : items1) { + assertFalse("pagination overlap is not allowed", items2.contains(s)); + } + for (String s : items2) { + assertFalse("pagination overlap is not allowed", items1.contains(s)); + } + + this.deleteIndex(IDX); + } + + @Test + public void testStatistics() { + NodeStatsResponse stats = null; + try { + stats = dbClient.stats(new NodeStatsRequest()); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(stats); + System.out.println(stats.getNodesInfo()); + System.out.println(stats.getNodeStatistics()); + } + + // @Test + public void testPreventAutoCreateIndex() { + final String IDX1 = "acidx1"; + final String ID1 = "acid1"; + final String IDX2 = "acidx2"; + final String ID2 = "acid2"; + final String OBJ = "{\"test\":5}"; + + ClusterSettingsResponse settingsResponse = null; + String esId = null; + // set setting to allow autocreate + try { + settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(settingsResponse); + assertTrue(settingsResponse.isAcknowledged()); + // test if something new can be created + esId = dbClient.doWriteRaw(IDX1, IDX1, ID1, OBJ); + assertEquals(ID1, esId); + // set setting to deny autocreate + try { + settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(false)); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(settingsResponse); + assertTrue(settingsResponse.isAcknowledged()); + // test if something new cannot be created + esId = dbClient.doWriteRaw(IDX2, IDX2, ID2, OBJ); + assertNull(esId); + // set setting to allow autocreate + try { + settingsResponse = dbClient.setupClusterSettings(new ClusterSettingsRequest(true)); + } catch (IOException e) { + fail(e.getMessage()); + } + assertNotNull(settingsResponse); + assertTrue(settingsResponse.isAcknowledged()); + + } + + private void deleteAlias(String idx, String alias) { + try { + dbClient.deleteAlias(new DeleteAliasRequest(idx, alias)); + } catch (IOException e) { + + } + } + + private void deleteIndex(String idx) { + try { + dbClient.deleteIndex(new DeleteIndexRequest(idx)); + } catch (IOException e) { + + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java index 32177d8df..883d48ac1 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestEsData.java @@ -42,74 +42,78 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntryList; */ public class TestEsData { - - @Test - public void testVersion() { - EsVersion version=null; - try { - version = new EsVersion("2.3.4"); - } catch (ParseException e) { - fail(e.getMessage()); - } - assertNotNull(version); - assertEquals(2, version.getMajor()); - assertEquals(3, version.getMinor()); - assertEquals(4, version.getRevision()); - - EsVersion versionNewer = new EsVersion(5,0,0); - EsVersion versionOlder = new EsVersion(2,2,0); - - assertTrue(version.isOlderOrEqualThan(versionNewer)); - assertTrue(version.isNewerOrEqualThan(versionOlder)); - - } - @Test - public void testIndices() { - IndicesEntryList list = new IndicesEntryList(); - IndicesEntry entry=null; - try { - entry=new IndicesEntry("yellow open inventoryequipment-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 2 3 1.2kb 2.4kb"); - list.add(entry); - list.add(new IndicesEntry("yellow open networkelement-connection-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); - list.add(new IndicesEntry("yellow open faultlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); - list.add(new IndicesEntry("yellow open eventlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); - } catch (ParseException e) { - fail(e.getMessage()); - } - assertEquals(4, list.size()); - assertNotNull(list.findByIndex("eventlog-v1")); - assertNull(list.findByIndex("faultcurrent")); - assertNotNull(entry); - assertEquals("yellow",entry.getStatus()); - assertEquals("open", entry.getStatus2()); - assertEquals("inventoryequipment-v1", entry.getName()); - assertEquals("5nNPRbJ3T9arMxqxBbJKyQ", entry.getHash()); - assertEquals(5, entry.getShards()); - assertEquals(1, entry.getReplicas()); - assertEquals(2, entry.getC1()); - assertEquals(3, entry.getC2()); - assertEquals("1.2kb", entry.getSize1()); - assertEquals("2.4kb", entry.getSize2()); - - } - @Test - public void testAliases() { - AliasesEntryList list = new AliasesEntryList(); - AliasesEntry entry=null; - try { - entry=new AliasesEntry("networkelement-connection networkelement-connection-v1 - - -"); - list.add(entry); - list.add(new AliasesEntry("faultcurrent faultcurrent-v1 - - -")); - list.add(new AliasesEntry("faultlog faultlog-v1 - - -")); - list.add(new AliasesEntry("maintenancemode maintenancemode-v1 - - -")); - } catch (ParseException e) { - fail(e.getMessage()); - } - assertEquals(4, list.size()); - assertNotNull(list.findByAlias("faultcurrent")); - assertNull(list.findByAlias("eventlog")); - assertNotNull(entry); - assertEquals("networkelement-connection",entry.getAlias()); - assertEquals("networkelement-connection-v1", entry.getIndex()); - } + + @Test + public void testVersion() { + EsVersion version = null; + try { + version = new EsVersion("2.3.4"); + } catch (ParseException e) { + fail(e.getMessage()); + } + assertNotNull(version); + assertEquals(2, version.getMajor()); + assertEquals(3, version.getMinor()); + assertEquals(4, version.getRevision()); + + EsVersion versionNewer = new EsVersion(5, 0, 0); + EsVersion versionOlder = new EsVersion(2, 2, 0); + + assertTrue(version.isOlderOrEqualThan(versionNewer)); + assertTrue(version.isNewerOrEqualThan(versionOlder)); + + } + + @Test + public void testIndices() { + IndicesEntryList list = new IndicesEntryList(); + IndicesEntry entry = null; + try { + entry = new IndicesEntry( + "yellow open inventoryequipment-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 2 3 1.2kb 2.4kb"); + list.add(entry); + list.add(new IndicesEntry( + "yellow open networkelement-connection-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); + list.add(new IndicesEntry("yellow open faultlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); + list.add(new IndicesEntry("yellow open eventlog-v1 5nNPRbJ3T9arMxqxBbJKyQ 5 1 0 0 1.2kb 1.2kb")); + } catch (ParseException e) { + fail(e.getMessage()); + } + assertEquals(4, list.size()); + assertNotNull(list.findByIndex("eventlog-v1")); + assertNull(list.findByIndex("faultcurrent")); + assertNotNull(entry); + assertEquals("yellow", entry.getStatus()); + assertEquals("open", entry.getStatus2()); + assertEquals("inventoryequipment-v1", entry.getName()); + assertEquals("5nNPRbJ3T9arMxqxBbJKyQ", entry.getHash()); + assertEquals(5, entry.getShards()); + assertEquals(1, entry.getReplicas()); + assertEquals(2, entry.getC1()); + assertEquals(3, entry.getC2()); + assertEquals("1.2kb", entry.getSize1()); + assertEquals("2.4kb", entry.getSize2()); + + } + + @Test + public void testAliases() { + AliasesEntryList list = new AliasesEntryList(); + AliasesEntry entry = null; + try { + entry = new AliasesEntry("networkelement-connection networkelement-connection-v1 - - -"); + list.add(entry); + list.add(new AliasesEntry("faultcurrent faultcurrent-v1 - - -")); + list.add(new AliasesEntry("faultlog faultlog-v1 - - -")); + list.add(new AliasesEntry("maintenancemode maintenancemode-v1 - - -")); + } catch (ParseException e) { + fail(e.getMessage()); + } + assertEquals(4, list.size()); + assertNotNull(list.findByAlias("faultcurrent")); + assertNull(list.findByAlias("eventlog")); + assertNotNull(entry); + assertEquals("networkelement-connection", entry.getAlias()); + assertEquals("networkelement-connection-v1", entry.getIndex()); + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java index d927ed750..72eba38e8 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestJsonAssert.java @@ -31,142 +31,143 @@ import org.onap.ccsdk.features.sdnr.wt.common.test.JSONAssert; public class TestJsonAssert { - @Test - public void testGenericTypes() { - try { - JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":true}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - try { - JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":2}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - try { - JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abc\"}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - - } - - @Test - public void testGenericTypesFails() { - try { - JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":false}", true); - fail("test boolean not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - try { - JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":3}", true); - fail("test int not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - try { - JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abcd\"}", true); - fail("test string not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - - } - - @Test - public void testObject() { - try { - JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", - "{ \"test\":{\"more\":{\"x\":1,\"z\":{},\"y\":\"2\"}}}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - - @Test - public void testObjectFails() { - try { - JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", - "{ \"test\":{\"more\":{\"x\":1,\"z\":{}}}}", true); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - } - - @Test - public void testArrayStrict() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"b\",\"c\"]}", true); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - - @Test - public void testArrayStrictFails() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"c\",\"b\"]}", true); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - } - - @Test - public void testArrayNonStrict() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"c\",\"b\"]}", false); - } catch (JSONException e) { - fail(e.getMessage()); - } - } - - @Test - public void testArrayNonStrictFails() { - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"c\",\"b\",\"d\"]}", false); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - try { - JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", - "{ \"test\":[\"a\",\"b\",\"d\"]}", false); - fail("test object not failed, but has to"); - } catch (JSONException e) { - fail("problem with json"); - } catch (AssertionError e) { - - } - } - - @Test - public void testNullParamCheck() { - - try { - - HtAssert.nonnull("test", new JSONArray(), null); - fail("exception not thrown"); - } catch (Exception e) { - assertTrue(e.getMessage().contains("org.onap.ccsdk.features.sdnr.wt.common.test.TestJsonAssert") && e.getMessage().contains("testNullParamCheck")); - } - } + @Test + public void testGenericTypes() { + try { + JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":true}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + try { + JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":2}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + try { + JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abc\"}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + + } + + @Test + public void testGenericTypesFails() { + try { + JSONAssert.assertEquals("test boolean", "{ \"test\":true}", "{ \"test\":false}", true); + fail("test boolean not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + try { + JSONAssert.assertEquals("test int", "{ \"test\":2}", "{ \"test\":3}", true); + fail("test int not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + try { + JSONAssert.assertEquals("test string", "{ \"test\":\"abc\"}", "{ \"test\":\"abcd\"}", true); + fail("test string not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + + } + + @Test + public void testObject() { + try { + JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", + "{ \"test\":{\"more\":{\"x\":1,\"z\":{},\"y\":\"2\"}}}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + + @Test + public void testObjectFails() { + try { + JSONAssert.assertEquals("test object", "{ \"test\":{\"more\":{\"x\":1,\"y\":\"2\",\"z\":{}}}}", + "{ \"test\":{\"more\":{\"x\":1,\"z\":{}}}}", true); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + } + + @Test + public void testArrayStrict() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"b\",\"c\"]}", true); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + + @Test + public void testArrayStrictFails() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"c\",\"b\"]}", true); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + } + + @Test + public void testArrayNonStrict() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"c\",\"b\"]}", false); + } catch (JSONException e) { + fail(e.getMessage()); + } + } + + @Test + public void testArrayNonStrictFails() { + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"c\",\"b\",\"d\"]}", false); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + try { + JSONAssert.assertEquals("test array strict", "{ \"test\":[\"a\",\"b\",\"c\"]}", + "{ \"test\":[\"a\",\"b\",\"d\"]}", false); + fail("test object not failed, but has to"); + } catch (JSONException e) { + fail("problem with json"); + } catch (AssertionError e) { + + } + } + + @Test + public void testNullParamCheck() { + + try { + + HtAssert.nonnull("test", new JSONArray(), null); + fail("exception not thrown"); + } catch (Exception e) { + assertTrue(e.getMessage().contains("org.onap.ccsdk.features.sdnr.wt.common.test.TestJsonAssert") + && e.getMessage().contains("testNullParamCheck")); + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java index 292856940..67c6c97f7 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPageHashMap.java @@ -26,37 +26,37 @@ import org.onap.ccsdk.features.sdnr.wt.common.database.responses.AggregationEntr public class TestPageHashMap { - @Test - public void testGenericTypes() { - AggregationEntries agg = new AggregationEntries(); + @Test + public void testGenericTypes() { + AggregationEntries agg = new AggregationEntries(); - for (int t=0; t < 100; t++) { - agg.put("Key"+t, Long.valueOf(t)); - } + for (int t = 0; t < 100; t++) { + agg.put("Key" + t, Long.valueOf(t)); + } - int x =0; - for (String k : agg.keySet()) { - if (x++ >= 10) - break; - System.out.println("Keys: "+k); - } + int x = 0; + for (String k : agg.keySet()) { + if (x++ >= 10) + break; + System.out.println("Keys: " + k); + } - String[] res; + String[] res; - res = agg.getKeysAsPagedStringList(5, 10); - System.out.println("Entries: "+res.length); - for (int t=0; t < res.length; t++) { - System.out.println("Entry "+t+": "+res[t]); - } + res = agg.getKeysAsPagedStringList(5, 10); + System.out.println("Entries: " + res.length); + for (int t = 0; t < res.length; t++) { + System.out.println("Entry " + t + ": " + res[t]); + } - res = agg.getKeysAsPagedStringList(5, 10); - System.out.println("Entries: "+res.length); - for (int t=0; t < res.length; t++) { - System.out.println("Entry "+t+": "+res[t]); - } + res = agg.getKeysAsPagedStringList(5, 10); + System.out.println("Entries: " + res.length); + for (int t = 0; t < res.length; t++) { + System.out.println("Entry " + t + ": " + res[t]); + } - } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java index a6f1b51b3..9de285d1b 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPomfile.java @@ -37,19 +37,17 @@ import org.xml.sax.SAXException; public class TestPomfile { - private static final String TESTPROPERTY_KEY="elasticsearch-rest-client.version"; + private static final String TESTPROPERTY_KEY = "elasticsearch-rest-client.version"; private static final String TESTPROPERTY_VALUE = "6.4.3"; private static final String POMFILENAME = "pom.xml"; - private static final String POM_PROPERTY = "#Generated by org.apache.felix.bundleplugin\n" + - "#Tue Nov 19 11:20:33 CET 2019\n" + - "version=0.7.0-SNAPSHOT\n" + - "groupId=org.onap.ccsdk.features.sdnr.wt\n" + - "artifactId=sdnr-wt-data-provider-provider\n"; + private static final String POM_PROPERTY = "#Generated by org.apache.felix.bundleplugin\n" + + "#Tue Nov 19 11:20:33 CET 2019\n" + "version=0.7.0-SNAPSHOT\n" + + "groupId=org.onap.ccsdk.features.sdnr.wt\n" + "artifactId=sdnr-wt-data-provider-provider\n"; //private static final Date DATE_EXPECTED = new Date(119, 10, 19, 11, 20, 33); @Test public void test() { - PomFile pom=null; + PomFile pom = null; try { pom = new PomFile(new FileInputStream(POMFILENAME)); } catch (ParserConfigurationException | SAXException | IOException e) { @@ -59,6 +57,7 @@ public class TestPomfile { assertEquals(TESTPROPERTY_VALUE, pom.getProperty(TESTPROPERTY_KEY)); } + @Test public void testProp() { PomPropertiesFile file = null; diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java index 379142db2..d073043c2 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/TestPortstatus.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * ============LICENSE_START======================================================================== * ONAP : ccsdk feature sdnr wt * ================================================================================================= @@ -14,7 +14,7 @@ * or implied. See the License for the specific language governing permissions and limitations under * the License. * ============LICENSE_END========================================================================== - ******************************************************************************/ + */ package org.onap.ccsdk.features.sdnr.wt.common.test; import static org.junit.Assert.assertFalse; @@ -29,47 +29,49 @@ import org.mockito.Mockito; import org.onap.ccsdk.features.sdnr.wt.common.database.Portstatus; import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo; -public class TestPortstatus extends Mockito{ +public class TestPortstatus extends Mockito { @Test public void testIsAvailable() throws IOException { - assertFalse("Port status should be false", Portstatus.isAvailable("localhost", 4567) ); + assertFalse("Port status should be false", Portstatus.isAvailable("localhost", 4567)); ServerSocket serverSocket = new ServerSocket(4567); - assertTrue("Port status should be true", Portstatus.isAvailable("localhost", 4567) ); + assertTrue("Port status should be true", Portstatus.isAvailable("localhost", 4567)); serverSocket.close(); } @Test public void testWaitIsAvailable() throws IOException { ServerSocket serverSocket = new ServerSocket(4567); - assertTrue("Port status should be true", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567) ); + assertTrue("Port status should be true", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567)); serverSocket.close(); } @Test public void testWaitIsAvailableHostInfo() throws IOException { ServerSocket serverSocket = new ServerSocket(4567); - assertTrue("Port status should be true", Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567)) ); + assertTrue("Port status should be true", + Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567))); serverSocket.close(); } @Test public void testWaitTillAvailable() throws IOException { Instant start = Instant.now(); - assertFalse("Port status should be false", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567) ); + assertFalse("Port status should be false", Portstatus.waitSecondsTillAvailable(5, "localhost", 4567)); Instant end = Instant.now(); long seconds = Duration.between(start, end).getSeconds(); - assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7 ); + assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7); } @Test public void testWaitTillAvailableHostinfo() throws IOException { Instant start = Instant.now(); - assertFalse("Port status should be false", Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567))); + assertFalse("Port status should be false", + Portstatus.waitSecondsTillAvailable(5, new HostInfo("localhost", 4567))); Instant end = Instant.now(); long seconds = Duration.between(start, end).getSeconds(); - assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7 ); + assertTrue("Port status timeout 5 expected and not between 3 .. 7 seconds", 3 < seconds && seconds < 7); } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java index 6ec47c230..a6f77c72d 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServlet.java @@ -29,99 +29,112 @@ import javax.servlet.http.HttpServletResponse; import org.onap.ccsdk.features.sdnr.wt.common.http.BaseServlet; -public class HelpServlet extends BaseServlet implements IPublicServlet{ - - /** - * - */ - private static final long serialVersionUID = 1L; - public static final String RESPONSE_GET = "This is the response get"; - public static final String RESPONSE_POST = "This is the response post"; - public static final String RESPONSE_PUT = "This is the response put"; - public static final String RESPONSE_DELETE = "This is the response delete"; - public static final String RESPONSE_OPTIONS = "This is the response options"; - private static final String HOST = "localhost"; - private int port; - private boolean isoff; - - /** - * @param port - */ - public HelpServlet(int port) { - this.port = port; - this.isoff=true; - } - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doGet(req, resp); - } - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doPost(req, resp); - } - @Override - public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doPut(req, resp); - } - @Override - public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - resp.setStatus(200); - } - @Override - public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - super.doDelete(req, resp); - } - @Override - protected String getOfflineResponse() { - return "offline"; - } - @Override - protected boolean isOff() { - return this.isoff; - } - @Override - protected boolean doTrustAll() { - // TODO Auto-generated method stub - return false; - } - @Override - protected void trustAll(boolean trust) { - // TODO Auto-generated method stub - - } - @Override - protected String getRemoteUrl(String uri) { - if (uri.startsWith("/")) { - uri = uri.substring(1); - } - if (uri.startsWith("base")) { - uri = uri.substring("base".length()); - } - if (uri.startsWith("/")) { - uri = uri.substring(1); - } - String base = "http://" + HOST + ":" + this.port; - if (!base.endsWith("/")) { - base += "/"; - } - - return base + uri; - } - @Override - protected boolean trustInsecure() { - // TODO Auto-generated method stub - return false; - } - @Override - protected boolean isCorsEnabled() { - // TODO Auto-generated method stub - return false; - } - /** - * @param b - */ - public void setOffline(boolean b) { - this.isoff = b; - - } +public class HelpServlet extends BaseServlet implements IPublicServlet { + + /** + * + */ + private static final long serialVersionUID = 1L; + public static final String RESPONSE_GET = "This is the response get"; + public static final String RESPONSE_POST = "This is the response post"; + public static final String RESPONSE_PUT = "This is the response put"; + public static final String RESPONSE_DELETE = "This is the response delete"; + public static final String RESPONSE_OPTIONS = "This is the response options"; + private static final String HOST = "localhost"; + private int port; + private boolean isoff; + + /** + * @param port + */ + public HelpServlet(int port) { + this.port = port; + this.isoff = true; + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doGet(req, resp); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doPost(req, resp); + } + + @Override + public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doPut(req, resp); + } + + @Override + public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + resp.setStatus(200); + } + + @Override + public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + super.doDelete(req, resp); + } + + @Override + protected String getOfflineResponse() { + return "offline"; + } + + @Override + protected boolean isOff() { + return this.isoff; + } + + @Override + protected boolean doTrustAll() { + // TODO Auto-generated method stub + return false; + } + + @Override + protected void trustAll(boolean trust) { + // TODO Auto-generated method stub + + } + + @Override + protected String getRemoteUrl(String uri) { + if (uri.startsWith("/")) { + uri = uri.substring(1); + } + if (uri.startsWith("base")) { + uri = uri.substring("base".length()); + } + if (uri.startsWith("/")) { + uri = uri.substring(1); + } + String base = "http://" + HOST + ":" + this.port; + if (!base.endsWith("/")) { + base += "/"; + } + + return base + uri; + } + + @Override + protected boolean trustInsecure() { + // TODO Auto-generated method stub + return false; + } + + @Override + protected boolean isCorsEnabled() { + // TODO Auto-generated method stub + return false; + } + + /** + * @param b + */ + public void setOffline(boolean b) { + this.isoff = b; + + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java index 8144e6eb7..c163c746f 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/HelpServletBase.java @@ -52,178 +52,179 @@ import com.sun.net.httpserver.HttpServer; public class HelpServletBase { - public static final String RESPONSE_GET = "This is the response get"; - public static final String RESPONSE_POST = "This is the response post"; - public static final String RESPONSE_PUT = "This is the response put"; - public static final String RESPONSE_DELETE = "This is the response delete"; - public static final String RESPONSE_OPTIONS = "This is the response options"; - - public static final String HTTPMETHOD_GET = "GET"; - public static final String HTTPMETHOD_POST = "POST"; - public static final String HTTPMETHOD_PUT = "PUT"; - public static final String HTTPMETHOD_DELETE = "DELETE"; - public static final String HTTPMETHOD_OPTIONS = "OPTIONS"; - private IPublicServlet servlet; - private static HttpServer server; - private static ExecutorService httpThreadPool; - - public final String HOST = "localhost"; - protected static int testPort; - private final String baseUri; - protected static final String LR = "\n"; - - public HelpServletBase(String baseuri, int port) { - this.baseUri=baseuri; - testPort = port; - } - - public void setServlet(IPublicServlet s) - { - this.servlet=s; - } - - protected void testrequest(String method, String data, String expectedResponse, boolean exact) { - this.testrequest("/mwtn/test",method, data, expectedResponse, exact, null); - } - protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact) { - this.testrequest(uri,method, data, expectedResponse, exact, null); - } - - protected void testrequest(String uri,String method, String data, String expectedResponse, boolean exact, - Map<String, String> headersToCheck) { - - HttpServletRequest mockRequest = mock(HttpServletRequest.class); - HttpServletResponse mockResponse = mock(HttpServletResponse.class); - - StringWriter out = new StringWriter(); - ServletOutputStream printOut = new ServletOutputStream() { - - @Override - public void write(int arg0) throws IOException { - out.write(arg0); - } - }; - ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); - ServletInputStream inputStream= new ServletInputStream() { - @Override - public int read() throws IOException { - return bis.read(); - } - }; - Vector<String> headers=new Vector<String>(); - headers.addElement("Accept"); - headers.add("User-Agent"); - Enumeration<String> headerNames = headers.elements(); - try { - when(mockRequest.getRequestURI()).thenReturn(this.baseUri+uri); - when(mockRequest.getHeaderNames()).thenReturn(headerNames); - when(mockRequest.getHeader("Accept")).thenReturn("application/json"); - when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc"); - when(mockRequest.getInputStream()).thenReturn(inputStream); - when(mockResponse.getOutputStream()).thenReturn(printOut); - System.out.println("do a " + method + " request"); - if (method == HTTPMETHOD_GET) - this.servlet.doGet(mockRequest, mockResponse); - else if (method == HTTPMETHOD_POST) - this.servlet.doPost(mockRequest, mockResponse); - else if (method == HTTPMETHOD_PUT) - this.servlet.doPut(mockRequest, mockResponse); - else if (method == HTTPMETHOD_DELETE) - this.servlet.doDelete(mockRequest, mockResponse); - else if (method == HTTPMETHOD_OPTIONS) - this.servlet.doOptions(mockRequest, mockResponse); - else - fail("http request method " + method + " test not implemented"); - } catch (Exception e) { - System.err.println(e.getMessage()); - } - - verify(mockResponse).setStatus(200); - if (exact) - assertEquals(expectedResponse, out.toString()); - else - assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse)); - // currently unable to check extra headers - if (headersToCheck != null) { - - } - } - @Before - private void init() throws IOException{ - - - initEsTestWebserver(testPort); - } - @After - private void deinit() { - stopTestWebserver(); - } - - public static void initEsTestWebserver(int port) throws IOException { - initEsTestWebserver(port, "/mwtn/test"); - } - public static void initEsTestWebserver(int port,String baseUri) throws IOException { - server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); - httpThreadPool = Executors.newFixedThreadPool(5); - server.setExecutor(httpThreadPool); - server.createContext(baseUri, new MyHandler()); - //server.createContext("/", new MyRootHandler()); - server.setExecutor(null); // creates a default executor - server.start(); - System.out.println("http server started"); - } - - public static void stopTestWebserver() { - if (server != null) { - server.stop(0); - httpThreadPool.shutdownNow(); - System.out.println("http server stopped" ); - } - } - - - - public static class MyHandler implements HttpHandler { - @Override - public void handle(HttpExchange t) throws IOException { - String method = t.getRequestMethod(); - System.out.println(String.format("req received: %s %s" ,method,t.getRequestURI())); - OutputStream os = null; - try { - if (method.equals(HTTPMETHOD_GET)) { - t.sendResponseHeaders(200, RESPONSE_GET.length()); - os = t.getResponseBody(); - os.write(RESPONSE_GET.getBytes()); - } else if (method.equals(HTTPMETHOD_POST)) { - t.sendResponseHeaders(200, RESPONSE_POST.length()); - os = t.getResponseBody(); - os.write(RESPONSE_POST.getBytes()); - } else if (method.equals(HTTPMETHOD_PUT)) { - t.sendResponseHeaders(200, RESPONSE_PUT.length()); - os = t.getResponseBody(); - os.write(RESPONSE_PUT.getBytes()); - } else if (method.equals(HTTPMETHOD_DELETE)) { - t.sendResponseHeaders(200, RESPONSE_DELETE.length()); - os = t.getResponseBody(); - os.write(RESPONSE_DELETE.getBytes()); - } else if (method.equals(HTTPMETHOD_OPTIONS)) { - t.sendResponseHeaders(200, RESPONSE_OPTIONS.length()); - //os = t.getResponseBody(); - //os.write(RESPONSE_OPTIONS.getBytes()); - } else { - t.sendResponseHeaders(404, 0); - } - System.out.println("req handled successful"); - - } catch (Exception e) { - System.out.println(e.getMessage()); - } - finally { - if (os != null) - { - os.close(); - } - } - } - } + public static final String RESPONSE_GET = "This is the response get"; + public static final String RESPONSE_POST = "This is the response post"; + public static final String RESPONSE_PUT = "This is the response put"; + public static final String RESPONSE_DELETE = "This is the response delete"; + public static final String RESPONSE_OPTIONS = "This is the response options"; + + public static final String HTTPMETHOD_GET = "GET"; + public static final String HTTPMETHOD_POST = "POST"; + public static final String HTTPMETHOD_PUT = "PUT"; + public static final String HTTPMETHOD_DELETE = "DELETE"; + public static final String HTTPMETHOD_OPTIONS = "OPTIONS"; + private IPublicServlet servlet; + private static HttpServer server; + private static ExecutorService httpThreadPool; + + public final String HOST = "localhost"; + protected static int testPort; + private final String baseUri; + protected static final String LR = "\n"; + + public HelpServletBase(String baseuri, int port) { + this.baseUri = baseuri; + testPort = port; + } + + public void setServlet(IPublicServlet s) { + this.servlet = s; + } + + protected void testrequest(String method, String data, String expectedResponse, boolean exact) { + this.testrequest("/mwtn/test", method, data, expectedResponse, exact, null); + } + + protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact) { + this.testrequest(uri, method, data, expectedResponse, exact, null); + } + + protected void testrequest(String uri, String method, String data, String expectedResponse, boolean exact, + Map<String, String> headersToCheck) { + + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + HttpServletResponse mockResponse = mock(HttpServletResponse.class); + + StringWriter out = new StringWriter(); + ServletOutputStream printOut = new ServletOutputStream() { + + @Override + public void write(int arg0) throws IOException { + out.write(arg0); + } + }; + ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes()); + ServletInputStream inputStream = new ServletInputStream() { + @Override + public int read() throws IOException { + return bis.read(); + } + }; + Vector<String> headers = new Vector<String>(); + headers.addElement("Accept"); + headers.add("User-Agent"); + Enumeration<String> headerNames = headers.elements(); + try { + when(mockRequest.getRequestURI()).thenReturn(this.baseUri + uri); + when(mockRequest.getHeaderNames()).thenReturn(headerNames); + when(mockRequest.getHeader("Accept")).thenReturn("application/json"); + when(mockRequest.getHeader("User-Agent")).thenReturn("Gecko abc"); + when(mockRequest.getInputStream()).thenReturn(inputStream); + when(mockResponse.getOutputStream()).thenReturn(printOut); + System.out.println("do a " + method + " request"); + if (method == HTTPMETHOD_GET) + this.servlet.doGet(mockRequest, mockResponse); + else if (method == HTTPMETHOD_POST) + this.servlet.doPost(mockRequest, mockResponse); + else if (method == HTTPMETHOD_PUT) + this.servlet.doPut(mockRequest, mockResponse); + else if (method == HTTPMETHOD_DELETE) + this.servlet.doDelete(mockRequest, mockResponse); + else if (method == HTTPMETHOD_OPTIONS) + this.servlet.doOptions(mockRequest, mockResponse); + else + fail("http request method " + method + " test not implemented"); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + + verify(mockResponse).setStatus(200); + if (exact) + assertEquals(expectedResponse, out.toString()); + else + assertTrue("response not for method " + method + "correct", out.toString().contains(expectedResponse)); + // currently unable to check extra headers + if (headersToCheck != null) { + + } + } + + @Before + private void init() throws IOException { + + + initEsTestWebserver(testPort); + } + + @After + private void deinit() { + stopTestWebserver(); + } + + public static void initEsTestWebserver(int port) throws IOException { + initEsTestWebserver(port, "/mwtn/test"); + } + + public static void initEsTestWebserver(int port, String baseUri) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0); + httpThreadPool = Executors.newFixedThreadPool(5); + server.setExecutor(httpThreadPool); + server.createContext(baseUri, new MyHandler()); + //server.createContext("/", new MyRootHandler()); + server.setExecutor(null); // creates a default executor + server.start(); + System.out.println("http server started"); + } + + public static void stopTestWebserver() { + if (server != null) { + server.stop(0); + httpThreadPool.shutdownNow(); + System.out.println("http server stopped"); + } + } + + + + public static class MyHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + String method = t.getRequestMethod(); + System.out.println(String.format("req received: %s %s", method, t.getRequestURI())); + OutputStream os = null; + try { + if (method.equals(HTTPMETHOD_GET)) { + t.sendResponseHeaders(200, RESPONSE_GET.length()); + os = t.getResponseBody(); + os.write(RESPONSE_GET.getBytes()); + } else if (method.equals(HTTPMETHOD_POST)) { + t.sendResponseHeaders(200, RESPONSE_POST.length()); + os = t.getResponseBody(); + os.write(RESPONSE_POST.getBytes()); + } else if (method.equals(HTTPMETHOD_PUT)) { + t.sendResponseHeaders(200, RESPONSE_PUT.length()); + os = t.getResponseBody(); + os.write(RESPONSE_PUT.getBytes()); + } else if (method.equals(HTTPMETHOD_DELETE)) { + t.sendResponseHeaders(200, RESPONSE_DELETE.length()); + os = t.getResponseBody(); + os.write(RESPONSE_DELETE.getBytes()); + } else if (method.equals(HTTPMETHOD_OPTIONS)) { + t.sendResponseHeaders(200, RESPONSE_OPTIONS.length()); + //os = t.getResponseBody(); + //os.write(RESPONSE_OPTIONS.getBytes()); + } else { + t.sendResponseHeaders(404, 0); + } + System.out.println("req handled successful"); + + } catch (Exception e) { + System.out.println(e.getMessage()); + } finally { + if (os != null) { + os.close(); + } + } + } + } } diff --git a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java index e6634d6a1..1d97b615a 100644 --- a/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java +++ b/sdnr/wt/common/src/test/java/org/onap/ccsdk/features/sdnr/wt/common/test/helper/IPublicServlet.java @@ -28,9 +28,13 @@ import javax.servlet.http.HttpServletResponse; public interface IPublicServlet { - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; - public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; - public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ; - public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException ; + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + + public void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + + public void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; + + public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; } |