diff --git a/src/main/java/ch/mno/copper/DataProvider.java b/src/main/java/ch/mno/copper/DataProvider.java index 9beb0d8..b9c3348 100644 --- a/src/main/java/ch/mno/copper/DataProvider.java +++ b/src/main/java/ch/mno/copper/DataProvider.java @@ -1,20 +1,13 @@ package ch.mno.copper; +import java.util.List; + import ch.mno.copper.collect.StoryTask; import ch.mno.copper.store.ValuesStore; import ch.mno.copper.stories.data.Story; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Created by dutoitc on 25.02.2016. - */ public interface DataProvider { - Set> getStoryTasks(); - List getStories(); StoryTask getStoryTask(Story story); diff --git a/src/main/java/ch/mno/copper/DataProviderImpl.java b/src/main/java/ch/mno/copper/DataProviderImpl.java index cd9e5e7..162c629 100644 --- a/src/main/java/ch/mno/copper/DataProviderImpl.java +++ b/src/main/java/ch/mno/copper/DataProviderImpl.java @@ -1,15 +1,14 @@ package ch.mno.copper; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import ch.mno.copper.collect.StoryTask; import ch.mno.copper.store.ValuesStore; import ch.mno.copper.stories.StoriesFacade; import ch.mno.copper.stories.data.Story; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - /** * Stories and values provider with cache. * At each call, it will load newer stories from disk, remove older from cache @@ -26,11 +25,6 @@ public DataProviderImpl(StoriesFacade storiesFacade, ValuesStore valuesStore) { refreshStoryTasks(); } - @Override - public Set> getStoryTasks() { - return cachedStoryTasks.entrySet(); - } - @Override public List getStories() { List stories = refreshStoryTasks(); diff --git a/src/main/java/ch/mno/copper/collect/BinaryCollectorWrapper.java b/src/main/java/ch/mno/copper/collect/BinaryCollectorWrapper.java index 22ad714..d1a7695 100644 --- a/src/main/java/ch/mno/copper/collect/BinaryCollectorWrapper.java +++ b/src/main/java/ch/mno/copper/collect/BinaryCollectorWrapper.java @@ -1,13 +1,7 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.BinaryConnector; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.helpers.SyntaxHelper; -import ch.mno.copper.stories.data.StoryGrammar; - import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -15,9 +9,10 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; -/** - * Created by dutoitc on 07.02.2016. - */ +import ch.mno.copper.collect.connectors.BinaryConnector; +import ch.mno.copper.helpers.SyntaxHelper; +import ch.mno.copper.stories.data.StoryGrammar; + public class BinaryCollectorWrapper extends AbstractCollectorWrapper { private final List checkElements; @@ -28,13 +23,14 @@ public BinaryCollectorWrapper(List checkElements) { results = new HashMap<>(checkElements.size()*4/3+1); } + @Override public List getAs() { return checkElements.stream().map(e->e.as).collect(Collectors.toList()); } @Override - public Map execute() throws ConnectorException { + public Map execute() { for (CheckElement el: checkElements) { boolean status; switch (el.cmd) { @@ -57,11 +53,11 @@ public Map execute() throws ConnectorException { @Override - public List> execute2D() throws ConnectorException { + public List> execute2D() { Map map = execute(); List> lst = new ArrayList<>(); for (CheckElement entry: checkElements) { - lst.add(Arrays.asList(map.get(entry.as))); + lst.add(List.of(map.get(entry.as))); } return lst; } diff --git a/src/main/java/ch/mno/copper/collect/JmxCollector.java b/src/main/java/ch/mno/copper/collect/JmxCollector.java index 30b0ac8..e66da74 100644 --- a/src/main/java/ch/mno/copper/collect/JmxCollector.java +++ b/src/main/java/ch/mno/copper/collect/JmxCollector.java @@ -1,18 +1,19 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.collect.connectors.JmxConnector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ReflectionException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.mno.copper.collect.connectors.JmxConnector; /** * Created by dutoitc on 29.01.2016. @@ -26,8 +27,8 @@ public String read(JmxConnector jmxConnector, String objectName, String attribut } - public static List jmxQueryWithCreds(String serverUrl, String username, String password, List queries) throws ConnectorException { - List results = new ArrayList(queries.size()); + public static List jmxQueryWithCreds(String serverUrl, String username, String password, List queries) { + List results = new ArrayList<>(queries.size()); JmxConnector conn = null; try { if (username==null) { @@ -57,10 +58,6 @@ public static List jmxQueryWithCreds(String serverUrl, String username, return results; } - public static List jmxQuery(String serverUrl, List queries) throws ConnectorException { - return jmxQueryWithCreds(serverUrl, null, null, queries); - } - public static class JmxQuery { protected String objectName; diff --git a/src/main/java/ch/mno/copper/collect/JmxCollectorWrapper.java b/src/main/java/ch/mno/copper/collect/JmxCollectorWrapper.java index 5b28946..c45a404 100644 --- a/src/main/java/ch/mno/copper/collect/JmxCollectorWrapper.java +++ b/src/main/java/ch/mno/copper/collect/JmxCollectorWrapper.java @@ -1,10 +1,5 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.helpers.NotImplementedException; -import ch.mno.copper.helpers.SyntaxHelper; -import ch.mno.copper.stories.data.StoryGrammar; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -12,6 +7,10 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import ch.mno.copper.helpers.NotImplementedException; +import ch.mno.copper.helpers.SyntaxHelper; +import ch.mno.copper.stories.data.StoryGrammar; + /** * Created by dutoitc on 07.02.2016. */ @@ -36,9 +35,9 @@ public List getAs() { } @Override - public Map execute() throws ConnectorException { + public Map execute() { List values = JmxCollector.jmxQueryWithCreds(url, username, password, jmxQueries); - Map map = new HashMap(); + Map map = new HashMap<>(); if (values.size()!=as.size()) { throw new RuntimeException("Wrong values number, expected " + as.size() + ", got " + values.size()); } @@ -49,7 +48,7 @@ public Map execute() throws ConnectorException { } @Override - public List> execute2D() throws ConnectorException { + public List> execute2D() { throw new NotImplementedException(); } diff --git a/src/main/java/ch/mno/copper/collect/SocketCollectorWrapper.java b/src/main/java/ch/mno/copper/collect/SocketCollectorWrapper.java index fef3e9e..c881462 100644 --- a/src/main/java/ch/mno/copper/collect/SocketCollectorWrapper.java +++ b/src/main/java/ch/mno/copper/collect/SocketCollectorWrapper.java @@ -1,14 +1,17 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.ConnectorException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import ch.mno.copper.collect.connectors.SocketConnector; import ch.mno.copper.helpers.SyntaxHelper; import ch.mno.copper.stories.data.StoryGrammar; -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * Created by dutoitc on 07.02.2016. */ @@ -34,9 +37,11 @@ public List getAs() { @Override - public Map execute() throws ConnectorException { - SocketConnector sc = new SocketConnector(host, port, timeout_ms); - SocketConnector.CONNECTION_CHECK status = sc.checkConnection(); + public Map execute() { + SocketConnector.CONNECTION_CHECK status; + try (SocketConnector sc = new SocketConnector(host, port, timeout_ms)) { + status = sc.checkConnection(); + } Map map = new HashMap<>(2); map.put(as.get(0), status.toString()); @@ -44,9 +49,11 @@ public Map execute() throws ConnectorException { } @Override - public List> execute2D() throws ConnectorException { - SocketConnector sc = new SocketConnector(host, port, timeout_ms); - SocketConnector.CONNECTION_CHECK status = sc.checkConnection(); + public List> execute2D() { + SocketConnector.CONNECTION_CHECK status; + try (SocketConnector sc = new SocketConnector(host, port, timeout_ms)) { + status = sc.checkConnection(); + } List> lst = new ArrayList<>(); List values = new ArrayList<>(); diff --git a/src/main/java/ch/mno/copper/collect/WebCollector.java b/src/main/java/ch/mno/copper/collect/WebCollector.java index 67c1726..7a2e28c 100644 --- a/src/main/java/ch/mno/copper/collect/WebCollector.java +++ b/src/main/java/ch/mno/copper/collect/WebCollector.java @@ -1,20 +1,7 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.HttpConnector; -import ch.mno.copper.collect.connectors.HttpResponseData; -import ch.mno.copper.collect.connectors.JmxConnector; -import com.jayway.jsonpath.JsonPath; -import com.jayway.jsonpath.PathNotFoundException; import net.minidev.json.JSONArray; -import org.apache.commons.lang3.tuple.Pair; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import javax.management.AttributeNotFoundException; -import javax.management.InstanceNotFoundException; -import javax.management.MBeanException; -import javax.management.MalformedObjectNameException; -import javax.management.ReflectionException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; @@ -23,9 +10,23 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Created by dutoitc on 29.01.2016. - */ +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ReflectionException; + +import org.apache.commons.lang3.tuple.Pair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.jayway.jsonpath.JsonPath; +import com.jayway.jsonpath.PathNotFoundException; + +import ch.mno.copper.collect.connectors.HttpConnector; +import ch.mno.copper.collect.connectors.HttpResponseData; +import ch.mno.copper.collect.connectors.JmxConnector; + public class WebCollector { private static Logger LOG = LoggerFactory.getLogger(WebCollector.class); @@ -82,7 +83,7 @@ public static List query(String url, String username, String password, L } static List extractValues(HttpResponseData data, List> valuesKept) { - List results = new ArrayList(valuesKept.size()); + List results = new ArrayList<>(valuesKept.size()); for (Pair value: valuesKept) { String key = value.getKey(); if ("responseCode".equals(key)) { diff --git a/src/main/java/ch/mno/copper/collect/WebCollectorWrapper.java b/src/main/java/ch/mno/copper/collect/WebCollectorWrapper.java index e99944f..675a6f9 100644 --- a/src/main/java/ch/mno/copper/collect/WebCollectorWrapper.java +++ b/src/main/java/ch/mno/copper/collect/WebCollectorWrapper.java @@ -1,12 +1,5 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.helpers.NotImplementedException; -import ch.mno.copper.helpers.SyntaxHelper; -import ch.mno.copper.stories.data.StoryGrammar; -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -14,6 +7,13 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; + +import ch.mno.copper.helpers.NotImplementedException; +import ch.mno.copper.helpers.SyntaxHelper; +import ch.mno.copper.stories.data.StoryGrammar; + /** * Created by dutoitc on 07.02.2016. */ @@ -37,14 +37,15 @@ public WebCollectorWrapper(String url, String username, String password, List getAs() { return as; } @Override - public Map execute() throws ConnectorException { + public Map execute() { List values = WebCollector.query(url, username, password, valuesKept); - Map map = new HashMap(); + Map map = new HashMap<>(); if (values.size()!=valuesKept.size()) { throw new RuntimeException("Wrong values number, expected " + valuesKept.size() + ", got " + values.size()); } @@ -55,7 +56,7 @@ public Map execute() throws ConnectorException { } @Override - public List> execute2D() throws ConnectorException { + public List> execute2D() { throw new NotImplementedException(); } @@ -100,7 +101,7 @@ public static WebCollectorWrapper buildCollector(StoryGrammar grammar, String st while (matcher3.find()) { String name1 = matcher3.group(1); String name2 = matcher3.group(2); - valuesKept.add(new ImmutablePair(name1, name2)); + valuesKept.add(new ImmutablePair<>(name1, name2)); } return new WebCollectorWrapper(url, username, password, valuesKept); } diff --git a/src/main/java/ch/mno/copper/collect/connectors/BinaryConnector.java b/src/main/java/ch/mno/copper/collect/connectors/BinaryConnector.java index a7f35c1..6195406 100644 --- a/src/main/java/ch/mno/copper/collect/connectors/BinaryConnector.java +++ b/src/main/java/ch/mno/copper/collect/connectors/BinaryConnector.java @@ -1,9 +1,5 @@ package ch.mno.copper.collect.connectors; -import ch.mno.copper.collect.BinaryCollectorWrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -12,18 +8,19 @@ import java.util.concurrent.Executors; import java.util.function.Consumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class BinaryConnector { - private static Logger LOG = LoggerFactory.getLogger(BinaryCollectorWrapper.class); + private static Logger LOG = LoggerFactory.getLogger(BinaryConnector.class); public static String executeCommand(String cmd){ ensureNotHavingCommandInjection(cmd); try { - Process process = Runtime.getRuntime().exec(String.format(cmd)); + Process process = Runtime.getRuntime().exec(cmd); StringBuilder sb = new StringBuilder(); - StringBuilder sbErr = new StringBuilder(); - Consumer consumer = (s->sb.append(s)); - Consumer consumerErr = (s->sbErr.append(s)); + Consumer consumer = (sb::append); StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer); StreamGobbler streamGobblerErr = new StreamGobbler(process.getErrorStream(), consumer); ExecutorService executorService = Executors.newFixedThreadPool(2); @@ -32,7 +29,7 @@ public static String executeCommand(String cmd){ int exitCode = process.waitFor(); Thread.sleep(100); executorService.shutdown(); - return sb.toString() + sbErr.toString() + (exitCode==0?"":"EXIT_"+exitCode); + return sb.toString() + (exitCode == 0 ? "" : "EXIT_" + exitCode); } catch (IOException | InterruptedException e) { LOG.trace("Exception: " + e.getMessage(), e); return "Exception: " + e.getMessage(); diff --git a/src/main/java/ch/mno/copper/collect/connectors/HttpConnector.java b/src/main/java/ch/mno/copper/collect/connectors/HttpConnector.java index 52f7234..81ac27a 100644 --- a/src/main/java/ch/mno/copper/collect/connectors/HttpConnector.java +++ b/src/main/java/ch/mno/copper/collect/connectors/HttpConnector.java @@ -1,5 +1,11 @@ package ch.mno.copper.collect.connectors; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.NameValuePair; @@ -16,12 +22,6 @@ import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * Created by dutoitc on 30.01.2016. */ @@ -60,7 +60,7 @@ public String post(String uri, Map values) throws ConnectorExcep HttpPost post = new HttpPost(uri); - final List nvps = new ArrayList(); + final List nvps = new ArrayList<>(); for (Map.Entry entry : values.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } @@ -123,6 +123,7 @@ public HttpResponseData get2(String uri) throws ConnectorException { } } + @Override public void close() { try { httpclient.close(); diff --git a/src/main/java/ch/mno/copper/collect/connectors/HttpResponseData.java b/src/main/java/ch/mno/copper/collect/connectors/HttpResponseData.java index bc2aada..8e80245 100644 --- a/src/main/java/ch/mno/copper/collect/connectors/HttpResponseData.java +++ b/src/main/java/ch/mno/copper/collect/connectors/HttpResponseData.java @@ -1,7 +1,5 @@ package ch.mno.copper.collect.connectors; -import org.apache.http.Header; - /** * Created by xsicdt on 12/10/17. */ diff --git a/src/main/java/ch/mno/copper/collect/connectors/JdbcConnector.java b/src/main/java/ch/mno/copper/collect/connectors/JdbcConnector.java index 41b1d32..3513fbc 100644 --- a/src/main/java/ch/mno/copper/collect/connectors/JdbcConnector.java +++ b/src/main/java/ch/mno/copper/collect/connectors/JdbcConnector.java @@ -1,6 +1,8 @@ package ch.mno.copper.collect.connectors; +import oracle.jdbc.OracleDriver; + import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; @@ -8,7 +10,6 @@ import java.sql.Statement; import java.util.ArrayList; import java.util.List; -import oracle.jdbc.OracleDriver; /** * Created by dutoitc on 31.01.2016. @@ -70,7 +71,7 @@ public List> query(String sql) throws ConnectorException { } @Override - public void close() throws Exception { + public void close() { try { connection.close(); } catch (SQLException e) { diff --git a/src/main/java/ch/mno/copper/daemon/CopperDaemon.java b/src/main/java/ch/mno/copper/daemon/CopperDaemon.java index b9e0d35..1cd8ea1 100644 --- a/src/main/java/ch/mno/copper/daemon/CopperDaemon.java +++ b/src/main/java/ch/mno/copper/daemon/CopperDaemon.java @@ -1,16 +1,5 @@ package ch.mno.copper.daemon; -import ch.mno.copper.DataProvider; -import ch.mno.copper.collect.StoryTask; -import ch.mno.copper.process.AbstractProcessor; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.stories.data.Story; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextRefreshedEvent; - -import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; @@ -20,9 +9,17 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -/** - * Created by dutoitc on 02.02.2016. - */ +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; + +import ch.mno.copper.DataProvider; +import ch.mno.copper.collect.StoryTask; +import ch.mno.copper.process.AbstractProcessor; +import ch.mno.copper.store.ValuesStore; +import ch.mno.copper.stories.data.Story; + // Optimisations: sleep until next task run (compute on task addition). Log next task run. public class CopperDaemon implements Runnable, ApplicationListener, AutoCloseable { @@ -32,9 +29,8 @@ public class CopperDaemon implements Runnable, ApplicationListener processors = new ArrayList<>(); - // private final ValuesStore valuesStore; private boolean shouldRun = true; - private List storiesToRun = new ArrayList<>(); + private final List storiesToRun = new ArrayList<>(); private LocalDateTime lastQueryTime = LocalDateTime.MIN; /** @@ -56,7 +52,7 @@ public void onApplicationEvent(ContextRefreshedEvent event) { } @Override - public void close() throws Exception { + public void close() { shouldRun = false; threadDaemon.interrupt(); } @@ -99,11 +95,7 @@ public void run() { runIteration(); // Save - try { - dataProvider.getValuesStore().save(); - } catch (IOException e) { - throw new RuntimeException("Cannot save to valuesStore"); - } + dataProvider.getValuesStore().save(); // Wait for some time LOG.trace("Daemon sleep"); diff --git a/src/main/java/ch/mno/copper/helpers/SyntaxHelper.java b/src/main/java/ch/mno/copper/helpers/SyntaxHelper.java index 8a851d5..727298c 100644 --- a/src/main/java/ch/mno/copper/helpers/SyntaxHelper.java +++ b/src/main/java/ch/mno/copper/helpers/SyntaxHelper.java @@ -1,13 +1,14 @@ package ch.mno.copper.helpers; -import ch.mno.copper.stories.data.StoryGrammar; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.mno.copper.stories.data.StoryGrammar; + /** * Created by xsicdt on 09/02/16. */ @@ -31,8 +32,8 @@ public static String checkSyntax(StoryGrammar grammar, String pattern, String va // System.out.println("DBG1>> " + key + ": " + Pattern.compile(grammar.getPattern(key), Pattern.DOTALL).matcher(value).find()); // } - StringBuffer sb = new StringBuffer(); - sb.append("Pattern \n >>>" + pattern + "\n does not match\n >>>" + value + "\n"); + StringBuilder sb = new StringBuilder(); + sb.append("Pattern \n >>>").append(pattern).append("\n does not match\n >>>").append(value).append("\n"); if (sbM.length()>0) { sb.append("But it matches the following patterns parts: ["); sb.append(sbM.toString().substring(0, sbM.length()-1)); @@ -49,7 +50,7 @@ public static String checkSyntax(StoryGrammar grammar, String pattern, String va for (int j = value.length()-1; j>1; j--) { String valuePart = value.substring(0, j); if (currPatternCompiled.matcher(valuePart).matches()) { - sb.append("Pattern start \n >>>" + currPattern + "\nmatches\n >>>" + valuePart+"\n\n"); + sb.append("Pattern start \n >>>").append(currPattern).append("\nmatches\n >>>").append(valuePart).append("\n\n"); throw new SyntaxException(sb.toString()); } } diff --git a/src/main/java/ch/mno/copper/process/Slf4jProcessor.java b/src/main/java/ch/mno/copper/process/Slf4jProcessor.java deleted file mode 100644 index 2bc6544..0000000 --- a/src/main/java/ch/mno/copper/process/Slf4jProcessor.java +++ /dev/null @@ -1,39 +0,0 @@ -package ch.mno.copper.process; - -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.report.Slf4jReporter; - -import java.util.Collection; -import java.util.List; - -/** - * Created by dutoitc on 02.02.2016. - */ -public class Slf4jProcessor extends AbstractProcessor { - - private Slf4jReporter reporter; - - public Slf4jProcessor(String name, List valuesTrigger) { - super(valuesTrigger); - reporter = new Slf4jReporter(name); - } - - @Override - public void trig(ValuesStore valueStore, Collection changedValueKeys) { - StringBuffer sb = new StringBuffer(); - sb.append("Values changed: "); - changedValueKeys.forEach(key -> { - if (sb.length() > 16) sb.append(','); - sb.append(key).append('=').append(valueStore.getValue(key)); - } - ); - if (sb.length() > 16) { - try { - reporter.report(sb.toString(), null); - } catch (ConnectorException e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/main/java/ch/mno/copper/report/CsvReporter.java b/src/main/java/ch/mno/copper/report/CsvReporter.java index 5d87eb4..173ae45 100644 --- a/src/main/java/ch/mno/copper/report/CsvReporter.java +++ b/src/main/java/ch/mno/copper/report/CsvReporter.java @@ -1,7 +1,5 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; - import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -16,7 +14,7 @@ public enum PARAMETERS {FILENAME, HEADERS, LINE}; @Override - public void report(String message, Map values) throws ConnectorException { + public void report(String message, Map values) { String filename = values.get(CsvReporter.PARAMETERS.FILENAME.toString()); String header = values.get(CsvReporter.PARAMETERS.HEADERS.toString()); String line = values.get(CsvReporter.PARAMETERS.LINE.toString()); diff --git a/src/main/java/ch/mno/copper/report/CsvReporterWrapper.java b/src/main/java/ch/mno/copper/report/CsvReporterWrapper.java index 0a82456..742054a 100644 --- a/src/main/java/ch/mno/copper/report/CsvReporterWrapper.java +++ b/src/main/java/ch/mno/copper/report/CsvReporterWrapper.java @@ -1,17 +1,13 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.stories.data.StoryGrammar; - import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Created by dutoitc on 07.02.2016. - */ +import ch.mno.copper.store.ValuesStore; +import ch.mno.copper.stories.data.StoryGrammar; + public class CsvReporterWrapper extends AbstractReporterWrapper { private StoryGrammar grammar; @@ -49,12 +45,7 @@ public void execute(Map values, ValuesStore valuesStore) { reporterValues.put(CsvReporter.PARAMETERS.HEADERS.toString(),headers); reporterValues.put(CsvReporter.PARAMETERS.LINE.toString(), message); - - try { - reporter.report(message, reporterValues); - } catch (ConnectorException e) { - e.printStackTrace(); - } + reporter.report(message, reporterValues); } } diff --git a/src/main/java/ch/mno/copper/report/MailReporter.java b/src/main/java/ch/mno/copper/report/MailReporter.java index 1104850..f384355 100644 --- a/src/main/java/ch/mno/copper/report/MailReporter.java +++ b/src/main/java/ch/mno/copper/report/MailReporter.java @@ -1,14 +1,13 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; +import java.util.Date; +import java.util.Map; + import org.apache.commons.mail.DefaultAuthenticator; import org.apache.commons.mail.HtmlEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Date; -import java.util.Map; - /** * Created by dutoitc on 31.01.2016. */ @@ -37,7 +36,7 @@ public MailReporter(String server, String serverUsername, String serverPassword, } @Override - public void report(String message, Map values) throws ConnectorException { + public void report(String message, Map values) { int currHour = new Date().getHours(); if (currHour==hour) { if (nbMessageInHour> MAX_MESSAGE_PER_HOUR) { diff --git a/src/main/java/ch/mno/copper/report/MailReporterWrapper.java b/src/main/java/ch/mno/copper/report/MailReporterWrapper.java index c33a021..737d805 100644 --- a/src/main/java/ch/mno/copper/report/MailReporterWrapper.java +++ b/src/main/java/ch/mno/copper/report/MailReporterWrapper.java @@ -1,18 +1,14 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.helpers.SyntaxHelper; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.stories.data.StoryGrammar; - import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Created by dutoitc on 07.02.2016. - */ +import ch.mno.copper.helpers.SyntaxHelper; +import ch.mno.copper.store.ValuesStore; +import ch.mno.copper.stories.data.StoryGrammar; + public class MailReporterWrapper extends AbstractReporterWrapper { private StoryGrammar grammar; @@ -56,12 +52,7 @@ public void execute(Map values, ValuesStore valuesStore) { reporterValues.put(MailReporter.PARAMETERS.TO.toString(),dest); reporterValues.put(MailReporter.PARAMETERS.BODY.toString(),message2); - - try { - reporter.report(message2, reporterValues); - } catch (ConnectorException e) { - e.printStackTrace(); - } + reporter.report(message2, reporterValues); } private String replaceValues(Map values, String message) { diff --git a/src/main/java/ch/mno/copper/report/Slf4jReporter.java b/src/main/java/ch/mno/copper/report/Slf4jReporter.java index dd3af95..9eccb6a 100644 --- a/src/main/java/ch/mno/copper/report/Slf4jReporter.java +++ b/src/main/java/ch/mno/copper/report/Slf4jReporter.java @@ -1,11 +1,10 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; +import java.util.Map; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Map; - /** * Created by dutoitc on 03.02.2016. */ @@ -18,7 +17,7 @@ public Slf4jReporter(String name) { logger = LoggerFactory.getLogger(name); } - public void report(String s, Map values) throws ConnectorException { + public void report(String s, Map values) { logger.info(s); } } diff --git a/src/main/java/ch/mno/copper/store/MapValuesStore.java b/src/main/java/ch/mno/copper/store/MapValuesStore.java index 34a55a5..a07dc82 100644 --- a/src/main/java/ch/mno/copper/store/MapValuesStore.java +++ b/src/main/java/ch/mno/copper/store/MapValuesStore.java @@ -1,14 +1,17 @@ package ch.mno.copper.store; -import ch.mno.copper.helpers.NotImplementedException; -import ch.mno.copper.store.data.InstantValues; - -import java.io.IOException; import java.time.Instant; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import ch.mno.copper.helpers.NotImplementedException; +import ch.mno.copper.store.data.InstantValues; + /** Map value store without date (only last values are kept) */ public class MapValuesStore implements ValuesStore { @@ -57,12 +60,12 @@ public List queryValues(Instant from, Instant to, long intervalSe } @Override - public void load() throws IOException { + public void load() { throw new NotImplementedException(); } @Override - public void save() throws IOException { + public void save() { throw new NotImplementedException(); } @@ -70,7 +73,7 @@ public void save() throws IOException { public Map getValuesMapString() { return map.values() .stream() - .collect(Collectors.toMap(a->a.getKey(), b->b.getValue())); + .collect(Collectors.toMap(StoreValue::getKey, StoreValue::getValue)); } @Override diff --git a/src/main/java/ch/mno/copper/store/ValuesStore.java b/src/main/java/ch/mno/copper/store/ValuesStore.java index f21da62..0cc09a6 100644 --- a/src/main/java/ch/mno/copper/store/ValuesStore.java +++ b/src/main/java/ch/mno/copper/store/ValuesStore.java @@ -1,13 +1,12 @@ package ch.mno.copper.store; -import ch.mno.copper.store.data.InstantValues; - -import java.io.IOException; import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Map; +import ch.mno.copper.store.data.InstantValues; + /** * Created by xsicdt on 25/08/17. */ @@ -31,9 +30,9 @@ public interface ValuesStore { List queryValues(Instant from, Instant to, long intervalSecond, List columns, int maxValues); - void load() throws IOException; + void load(); - void save() throws IOException; + void save(); @Deprecated // Use getValues() Map getValuesMapString(); diff --git a/src/main/java/ch/mno/copper/store/db/DBServer.java b/src/main/java/ch/mno/copper/store/db/DBServer.java index e68aa31..529b58a 100644 --- a/src/main/java/ch/mno/copper/store/db/DBServer.java +++ b/src/main/java/ch/mno/copper/store/db/DBServer.java @@ -1,12 +1,5 @@ package ch.mno.copper.store.db; -import ch.mno.copper.store.StoreValue; -import ch.mno.copper.store.data.InstantValue; -import ch.mno.copper.store.data.InstantValues; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -17,6 +10,15 @@ import java.util.Collection; import java.util.List; +import javax.sql.DataSource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.mno.copper.store.StoreValue; +import ch.mno.copper.store.data.InstantValue; +import ch.mno.copper.store.data.InstantValues; + /** * Helper to readInstant-write store to a local H2 Database. The DB is automatically created if not existent. * Time is from-inclusive, to-exclusive like String.substring. @@ -65,7 +67,7 @@ private long nextSequence() throws SQLException { /** * Insert a value at given instant. Actuve value will be finished at the same instant. no store is inserted if current value is the same value */ - public void insert(String key, String value, Instant instant) throws SQLException { + public void insert(String key, String value, Instant instant) { String sqlInsert = "INSERT INTO valuestore ( idvaluestore, key, value, datefrom, dateto) VALUES (?,?,?,?,?)"; String sqlUpdatePrevious = "update valuestore set dateto=? where idvaluestore=?"; @@ -84,7 +86,9 @@ public void insert(String key, String value, Instant instant) throws SQLExceptio } } } - if (value==null ) value=""; + if (value==null ) { + value=""; + } long id = nextSequence(); stmt.setLong(1, id); @@ -119,7 +123,7 @@ public void insert(String key, String value, Instant instant) throws SQLExceptio /** * Read the 'key' value at given instant */ - public StoreValue read(String key, Instant timestamp) throws SQLException { + public StoreValue read(String key, Instant timestamp) { String sql = "SELECT idvaluestore, key, value, datefrom, dateto FROM valuestore where key=? and datefrom<=? and dateto>? order by datefrom"; try (Connection con = cp.getConnection(); PreparedStatement stmt = con.prepareStatement(sql)) { @@ -134,7 +138,7 @@ public StoreValue read(String key, Instant timestamp) throws SQLException { } } - if (values.size() == 0) { + if (values.isEmpty()) { return null; } if (values.size() == 1) { @@ -148,7 +152,7 @@ public StoreValue read(String key, Instant timestamp) throws SQLException { throw new RuntimeException("Too much value for key=" + key + ", instant=" + timestamp.getEpochSecond()); } - public List readInstant(List keys, Instant timestampFrom, Instant timestampTo, long intervalSeconds, int maxValues) throws SQLException { + public List readInstant(List keys, Instant timestampFrom, Instant timestampTo, long intervalSeconds, int maxValues) { String sql = "select * from (" + "select ts,c1, value, idValueStore, key from ( " + "select ts, c1 from ( " + @@ -199,7 +203,7 @@ public List readInstant(List keys, Instant timestampFrom /** * Read all values for a given key active between from, to. (could have been inserted before and finish after) */ - public List read(String key, Instant timestampFrom, Instant timestampTo, int maxValues) throws SQLException { + public List read(String key, Instant timestampFrom, Instant timestampTo, int maxValues) { if (timestampTo.isAfter(Instant.now())) { timestampTo = Instant.now(); } @@ -234,7 +238,7 @@ public List read(String key, Instant timestampFrom, Instant timestam /** * Read the latest value of a key) */ - public StoreValue readLatest(String key) throws SQLException { + public StoreValue readLatest(String key) { try (Connection con = cp.getConnection(); PreparedStatement stmt = con.prepareStatement("SELECT idvaluestore, key, value, datefrom, dateto FROM valuestore where key=? and dateto=?")) { stmt.setString(1, key); @@ -251,7 +255,7 @@ public StoreValue readLatest(String key) throws SQLException { /** * Read all latest values */ - public List readLatest() throws SQLException { + public List readLatest() { List values = new ArrayList<>(); try (Connection con = cp.getConnection(); PreparedStatement stmt = con.prepareStatement("SELECT idvaluestore, key, value, datefrom, dateto,\n" + diff --git a/src/main/java/ch/mno/copper/store/db/DBValuesStore.java b/src/main/java/ch/mno/copper/store/db/DBValuesStore.java index a64fe04..435b2d6 100644 --- a/src/main/java/ch/mno/copper/store/db/DBValuesStore.java +++ b/src/main/java/ch/mno/copper/store/db/DBValuesStore.java @@ -1,11 +1,5 @@ package ch.mno.copper.store.db; -import ch.mno.copper.store.StoreValue; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.store.data.InstantValues; - -import java.io.IOException; -import java.sql.SQLException; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; @@ -13,6 +7,10 @@ import java.util.Map; import java.util.stream.Collectors; +import ch.mno.copper.store.StoreValue; +import ch.mno.copper.store.ValuesStore; +import ch.mno.copper.store.data.InstantValues; + /** * Created by dutoitc on 19.09.2017. */ @@ -26,19 +24,11 @@ public DBValuesStore(DBServer server) { @Override public void put(String key, String value) { - try { - server.insert(key, value, Instant.now()); - } catch (SQLException e) { - throw new RuntimeException(e); - } + server.insert(key, value, Instant.now()); } public void put(String key, String value, Instant d) { - try { - server.insert(key, value, d); - } catch (SQLException e) { - throw new RuntimeException(e); - } + server.insert(key, value, d); } public void clearAllData() { @@ -47,12 +37,7 @@ public void clearAllData() { @Override public String getValue(String key) { - StoreValue storeValue = null; - try { - storeValue = server.readLatest(key); - } catch (SQLException e) { - throw new RuntimeException("Cannot readInstant value " + key + ": " + e.getMessage()); - } + StoreValue storeValue = server.readLatest(key); if (storeValue == null) { return ""; // no store } @@ -61,12 +46,8 @@ public String getValue(String key) { @Override public Map getValues() { - try { - return server.readLatest().stream() - .collect(Collectors.toMap(x -> x.getKey(), x -> x, (a,b)->b)); // Ignoring duplicate, keep last - } catch (SQLException e) { - throw new RuntimeException("Cannot readInstant values: " + e.getMessage(), e); - } + return server.readLatest().stream() + .collect(Collectors.toMap(StoreValue::getKey, x -> x, (a, b)->b)); // Ignoring duplicate, keep last } @Override @@ -78,42 +59,30 @@ public Collection queryValues(Instant from, Instant to) { public List queryValues(Instant from, Instant to, List columns, int maxValues) { List values = new ArrayList<>(); for (String key : columns) { - try { - values.addAll(server.read(key, from, to, maxValues)); - } catch (SQLException e) { - throw new RuntimeException(e.getMessage(), e); - } + values.addAll(server.read(key, from, to, maxValues)); } return values; } @Override public List queryValues(Instant from, Instant to, long intervalSecond, List columns, int maxValues) { - try { - return server.readInstant(columns, from, to, intervalSecond, maxValues); - } catch (SQLException e) { - throw new RuntimeException(e.getMessage(), e); - } + return server.readInstant(columns, from, to, intervalSecond, maxValues); } @Override - public void load() throws IOException { + public void load() { } @Override - public void save() throws IOException { + public void save() { } @Override public Map getValuesMapString() { - try { - return server.readLatest().stream() - .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue())); - } catch (SQLException e) { - throw new RuntimeException("Cannot readInstant values: " + e.getMessage(), e); - } + return server.readLatest().stream() + .collect(Collectors.toMap(StoreValue::getKey, StoreValue::getValue)); } @Override diff --git a/src/main/java/ch/mno/copper/store/db/InstantValueMapper.java b/src/main/java/ch/mno/copper/store/db/InstantValueMapper.java index bdae99a..c6f7fe9 100644 --- a/src/main/java/ch/mno/copper/store/db/InstantValueMapper.java +++ b/src/main/java/ch/mno/copper/store/db/InstantValueMapper.java @@ -1,20 +1,29 @@ package ch.mno.copper.store.db; -import ch.mno.copper.store.data.InstantValue; - import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Timestamp; import java.time.Instant; +import ch.mno.copper.store.data.InstantValue; + public class InstantValueMapper { static InstantValue map(ResultSet rs) throws SQLException { long idValueStore = rs.getLong("idValueStore"); - if (idValueStore == 0) idValueStore = -1; // TODO: check if id is null, not zero + if (idValueStore == 0) { + idValueStore = -1; // TODO: check if id is null, not zero + } String dbKey = rs.getString("c1"); String value = rs.getString("value"); - if (value == null) value = ""; - Instant ts = rs.getTimestamp("ts").toInstant(); + if (value == null) { + value = ""; + } + Timestamp timestamp = rs.getTimestamp("ts"); + Instant ts = null; + if (timestamp != null) { + ts = timestamp.toInstant(); + } return new InstantValue(idValueStore, dbKey, value, ts); } diff --git a/src/main/java/ch/mno/copper/store/db/StoreValueMapper.java b/src/main/java/ch/mno/copper/store/db/StoreValueMapper.java index de45670..8044086 100644 --- a/src/main/java/ch/mno/copper/store/db/StoreValueMapper.java +++ b/src/main/java/ch/mno/copper/store/db/StoreValueMapper.java @@ -1,12 +1,11 @@ package ch.mno.copper.store.db; -import ch.mno.copper.store.StoreValue; -import org.h2.jdbc.JdbcSQLException; - import java.sql.ResultSet; import java.sql.SQLException; import java.time.Instant; +import ch.mno.copper.store.StoreValue; + public class StoreValueMapper { static StoreValue map(ResultSet rs, boolean wantNbValues) throws SQLException { diff --git a/src/main/java/ch/mno/copper/stories/DiskHelper.java b/src/main/java/ch/mno/copper/stories/DiskHelper.java index e344550..ecd0ca6 100644 --- a/src/main/java/ch/mno/copper/stories/DiskHelper.java +++ b/src/main/java/ch/mno/copper/stories/DiskHelper.java @@ -2,7 +2,6 @@ import config.CopperScreensProperties; import config.CopperStoriesProperties; -import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; @@ -20,6 +19,8 @@ import java.util.List; import java.util.Map; +import org.apache.commons.io.FileUtils; + public class DiskHelper { public final CopperStoriesProperties copperStoriesProperties; @@ -90,8 +91,12 @@ public List findStoryNames() { public void ensureStoriesFolderExists() { File fstoriesFolder = new File(storiesFolder); - if (fstoriesFolder.isFile()) throw new RuntimeException("stories should be a folder, not a file"); - if (!fstoriesFolder.exists()) fstoriesFolder.mkdir(); + if (fstoriesFolder.isFile()) { + throw new RuntimeException("stories should be a folder, not a file"); + } + if (!fstoriesFolder.exists()) { + fstoriesFolder.mkdir(); + } } public FileInputStream getStoryAsStream(String storyName) throws FileNotFoundException { @@ -103,7 +108,7 @@ public Map findScreens() { if (new File(screensFolder).exists()) { try { Files.list(Path.of(screensFolder)) - .sorted(Comparator.comparing(a -> a.getFileName())) + .sorted(Comparator.comparing(Path::getFileName)) .filter(a->a.getFileName().toString().endsWith(".json")) .forEach(a-> { try { diff --git a/src/main/java/ch/mno/copper/stories/StoriesFacade.java b/src/main/java/ch/mno/copper/stories/StoriesFacade.java index f4279c4..c0824f8 100644 --- a/src/main/java/ch/mno/copper/stories/StoriesFacade.java +++ b/src/main/java/ch/mno/copper/stories/StoriesFacade.java @@ -1,5 +1,9 @@ package ch.mno.copper.stories; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.List; + import ch.mno.copper.collect.StoryTask; import ch.mno.copper.collect.connectors.ConnectorException; import ch.mno.copper.store.ValuesStore; @@ -7,17 +11,12 @@ import ch.mno.copper.stories.data.StoryGrammar; import ch.mno.copper.stories.data.StoryValidationResult; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; - public interface StoriesFacade { StoryGrammar getGrammar(); List getStories(boolean shouldRefreshFromDisk); - Story buildStory(FileInputStream fileInputStream, String storyName) throws IOException, ConnectorException; + Story buildStory(FileInputStream fileInputStream, String storyName) throws IOException; StoryTask buildStoryTask(Story story, ValuesStore valuesStore); diff --git a/src/main/java/ch/mno/copper/stories/StoriesFacadeImpl.java b/src/main/java/ch/mno/copper/stories/StoriesFacadeImpl.java index 4ee567b..16791d7 100644 --- a/src/main/java/ch/mno/copper/stories/StoriesFacadeImpl.java +++ b/src/main/java/ch/mno/copper/stories/StoriesFacadeImpl.java @@ -1,5 +1,13 @@ package ch.mno.copper.stories; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import ch.mno.copper.collect.StoryTask; import ch.mno.copper.collect.connectors.ConnectorException; import ch.mno.copper.helpers.SyntaxException; @@ -8,17 +16,7 @@ import ch.mno.copper.stories.data.Story; import ch.mno.copper.stories.data.StoryGrammar; import ch.mno.copper.stories.data.StoryValidationResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -/** - * Created by dutoitc on 23.02.2016. - */ public class StoriesFacadeImpl implements StoriesFacade { private Logger LOG = LoggerFactory.getLogger(StoriesFacadeImpl.class); @@ -43,7 +41,7 @@ public List getStories(boolean shouldRefreshFromDisk) { } @Override - public Story buildStory(FileInputStream fileInputStream, String storyName) throws IOException, ConnectorException { + public Story buildStory(FileInputStream fileInputStream, String storyName) throws IOException { return new Story(grammar, fileInputStream, storyName); } @@ -119,8 +117,6 @@ public void refreshFromDisk() { storiesHolder.markAsError(storyName); } catch (IOException e) { e.printStackTrace(); - } catch (ConnectorException e) { - e.printStackTrace(); } catch (RuntimeException e) { //e.printStackTrace(); // Too verbose yet: invalid stories log errors on each story refresh, every second or so diff --git a/src/main/java/ch/mno/copper/stories/StoryTaskBuilder.java b/src/main/java/ch/mno/copper/stories/StoryTaskBuilder.java index baf157f..0d55909 100644 --- a/src/main/java/ch/mno/copper/stories/StoryTaskBuilder.java +++ b/src/main/java/ch/mno/copper/stories/StoryTaskBuilder.java @@ -1,18 +1,22 @@ package ch.mno.copper.stories; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import ch.mno.copper.collect.AbstractCollectorWrapper; import ch.mno.copper.collect.StoryTask; import ch.mno.copper.collect.StoryTaskImpl; import ch.mno.copper.report.AbstractReporterWrapper; import ch.mno.copper.store.ValuesStore; import ch.mno.copper.stories.data.Story; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.*; -import java.util.stream.Collectors; public class StoryTaskBuilder { @@ -42,7 +46,7 @@ public static StoryTask build(Story story, ValuesStore valuesStore) { // Report AbstractReporterWrapper reporter = story.getReporterWrapper(); if (reporter == null) { - values.forEach((key, value) -> valuesStore.put(key, value)); + values.forEach(valuesStore::put); } else { reporter.execute(values, valuesStore); } @@ -52,9 +56,7 @@ public static StoryTask build(Story story, ValuesStore valuesStore) { private static Map collect(Story story, ValuesStore valuesStore) { AbstractCollectorWrapper collectorWrapper = story.getCollectorWrapper(); if (collectorWrapper == null) { // Null means to readInstant value store - Map values = new HashMap<>(); - values.putAll(valuesStore.getValuesMapString()); - return values; + return new HashMap<>(valuesStore.getValuesMapString()); } // Execute with timeout diff --git a/src/main/java/ch/mno/copper/stories/data/MatchedPattern.java b/src/main/java/ch/mno/copper/stories/data/MatchedPattern.java index b21a9c3..1c75e84 100644 --- a/src/main/java/ch/mno/copper/stories/data/MatchedPattern.java +++ b/src/main/java/ch/mno/copper/stories/data/MatchedPattern.java @@ -1,6 +1,7 @@ package ch.mno.copper.stories.data; import java.io.Serializable; +import java.util.Objects; /** * Created by dutoitc on 27.04.2019. @@ -50,9 +51,9 @@ public boolean equals(Object o) { if (start != that.start) return false; if (end != that.end) return false; - if (patternName != null ? !patternName.equals(that.patternName) : that.patternName != null) return false; - if (patternShort != null ? !patternShort.equals(that.patternShort) : that.patternShort != null) return false; - return patternFull != null ? patternFull.equals(that.patternFull) : that.patternFull == null; + if (!Objects.equals(patternName, that.patternName)) return false; + if (!Objects.equals(patternShort, that.patternShort)) return false; + return Objects.equals(patternFull, that.patternFull); } @Override diff --git a/src/main/java/ch/mno/copper/stories/data/Story.java b/src/main/java/ch/mno/copper/stories/data/Story.java index 7b47e19..a56df62 100644 --- a/src/main/java/ch/mno/copper/stories/data/Story.java +++ b/src/main/java/ch/mno/copper/stories/data/Story.java @@ -1,16 +1,5 @@ package ch.mno.copper.stories.data; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.collect.AbstractCollectorWrapper; -import ch.mno.copper.collect.CollectorWrapperFactory; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.helpers.SyntaxException; -import ch.mno.copper.helpers.SyntaxHelper; -import ch.mno.copper.report.AbstractReporterWrapper; -import org.apache.commons.io.IOUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -18,6 +7,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.mno.copper.collect.AbstractCollectorWrapper; +import ch.mno.copper.collect.CollectorWrapperFactory; +import ch.mno.copper.helpers.SyntaxException; +import ch.mno.copper.helpers.SyntaxHelper; +import ch.mno.copper.report.AbstractReporterWrapper; +import ch.mno.copper.store.ValuesStore; + /** * Created by dutoitc on 07.02.2016. */ @@ -34,12 +34,12 @@ public class Story { private transient AbstractReporterWrapper reporterWrapper; - public Story(StoryGrammar grammar, String storyName, String storyText) throws IOException, ConnectorException { + public Story(StoryGrammar grammar, String storyName, String storyText) throws IOException { this(grammar, new ByteArrayInputStream(storyText.getBytes()), storyName); } - public Story(StoryGrammar grammar, InputStream is, String storyName) throws IOException, ConnectorException { + public Story(StoryGrammar grammar, InputStream is, String storyName) throws IOException { this.storyName = storyName; storyText = IOUtils.toString(is); storyText = Pattern.compile("#.*?\n", Pattern.DOTALL).matcher(storyText).replaceAll(""); // Remove comments lines @@ -156,7 +156,7 @@ static boolean matchWhen(String storedValue, String operator, String expectedVal case ">": return a > b; case "=": - return Math.abs(a.floatValue() - b.floatValue()) < Math.abs(a.floatValue() / 25); + return Math.abs(a - b) < Math.abs(a / 25); default: throw new RuntimeException("Unsuppported operator " + operator); } @@ -181,7 +181,7 @@ public String getError() { } - private class When { + private static class When { private final String variable; private final String operator; private final String value; diff --git a/src/main/java/ch/mno/copper/stories/data/StoryGrammar.java b/src/main/java/ch/mno/copper/stories/data/StoryGrammar.java index c6287f5..5aaf264 100644 --- a/src/main/java/ch/mno/copper/stories/data/StoryGrammar.java +++ b/src/main/java/ch/mno/copper/stories/data/StoryGrammar.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -19,7 +20,7 @@ public class StoryGrammar { private Map values = new HashMap<>(); public StoryGrammar(InputStream source) { - try (BufferedReader br = new BufferedReader(new InputStreamReader(source, "UTF-8"))) { + try (BufferedReader br = new BufferedReader(new InputStreamReader(source, StandardCharsets.UTF_8))) { String line; int noLine = 0; while ((line = br.readLine()) != null) { diff --git a/src/main/java/ch/mno/copper/web/CopperServices.java b/src/main/java/ch/mno/copper/web/CopperController.java similarity index 71% rename from src/main/java/ch/mno/copper/web/CopperServices.java rename to src/main/java/ch/mno/copper/web/CopperController.java index 70884e0..307b041 100644 --- a/src/main/java/ch/mno/copper/web/CopperServices.java +++ b/src/main/java/ch/mno/copper/web/CopperController.java @@ -1,6 +1,40 @@ package ch.mno.copper.web; -import ch.mno.copper.collect.connectors.ConnectorException; +import io.swagger.annotations.ApiOperation; + +import java.io.IOException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; + +import org.jfree.chart.JFreeChart; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.util.StreamUtils; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + import ch.mno.copper.daemon.CopperDaemon; import ch.mno.copper.helpers.GraphHelper; import ch.mno.copper.store.StoreValue; @@ -17,30 +51,12 @@ import ch.mno.copper.web.dto.StoryPostDTO; import ch.mno.copper.web.dto.StoryWEBDTO; import ch.mno.copper.web.helpers.InstantHelper; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import io.swagger.annotations.ApiOperation; -import org.jfree.chart.JFreeChart; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.util.StreamUtils; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.server.ResponseStatusException; - -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import java.io.IOException; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; @RestController @RequestMapping(value = "/ws", produces = MediaType.APPLICATION_JSON, consumes = MediaType.WILDCARD) -public class CopperServices { +public class CopperController { + + private static Logger LOG = LoggerFactory.getLogger(CopperController.class); private final ValuesStore valuesStore; private final StoriesFacade storiesFacade; @@ -49,7 +65,7 @@ public class CopperServices { @Autowired private DiskHelper diskHelper; - public CopperServices(ValuesStore valuesStore, final StoriesFacade storiesFacade, final CopperDaemon daemon) { + public CopperController(ValuesStore valuesStore, final StoriesFacade storiesFacade, final CopperDaemon daemon) { this.valuesStore = valuesStore; this.storiesFacade = storiesFacade; this.daemon = daemon; @@ -87,7 +103,7 @@ public StoryValidationResult postStory(@RequestBody String story) { @PostMapping(value = "story/{storyName}", produces = MediaType.TEXT_PLAIN) @ApiOperation(value = "Method to create a new story", notes = "Use this to store a story. If originalStoryName='new', a new story is saved and 'Ok' is returned. otherwise the story will be updated by storyName (originalStoryName)") - public ResponseEntity postStory(@PathVariable("storyName") String storyName, @RequestBody StoryPostDTO post) throws IOException, ConnectorException { + public ResponseEntity postStory(@PathVariable("storyName") String storyName, @RequestBody StoryPostDTO post) { StoriesFacade sf = getStoriesFacade(); // Create @@ -104,13 +120,12 @@ public ResponseEntity postStory(@PathVariable("storyName") String storyN Story story = sf.getStoryByName(storyName); if (story == null) { throw new RuntimeException("Story " + storyName + " was not found"); - } else { - try { - String msg = sf.updateStory(post.getOriginalStoryName(), post.getStoryName(), post.getStoryText()); - return ResponseEntity.of(Optional.of(msg)); - } catch (Exception e) { - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } + } + try { + String msg = sf.updateStory(post.getOriginalStoryName(), post.getStoryName(), post.getStoryText()); + return ResponseEntity.of(Optional.of(msg)); + } catch (Exception e) { + throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } } @@ -120,10 +135,9 @@ public ResponseEntity postStory(@PathVariable("storyName") String storyN public String getValues() { try { Map values = valuesStore.getValues(); - String json = buildGson().toJson(values); - return json; + return buildGson().toJson(values); } catch (Exception e) { - e.printStackTrace(); + LOG.error("Error", e); throw e; } } @@ -159,12 +173,12 @@ public String deleteValuesOfKey(@PathVariable String key) { @GetMapping(value = "values/query") @ApiOperation(value = "Retrieve values between date", notes = "(from null means from 2000, to null means now). Warning, retrieving many dates could be time-consuming and generate high volume of store") - public ResponseEntity getValues(@QueryParam("from") String dateFrom, - @QueryParam("to") String dateTo, - @QueryParam("columns") String columns, - @DefaultValue("100") @QueryParam("maxvalues") Integer maxValues) { + public ResponseEntity getValues(@RequestParam(value = "from", required = false) String dateFrom, + @RequestParam(value = "to", required = false) String dateTo, + @RequestParam(value = "columns", required = false) String columns, + @RequestParam(value = "maxvalues", required = false, defaultValue = "100") Integer maxValues) { if (columns == null) { - return new ResponseEntity("Missing 'columns'", HttpStatus.NOT_ACCEPTABLE); + return new ResponseEntity<>("Missing 'columns'", HttpStatus.NOT_ACCEPTABLE); } Instant from = InstantHelper.findInstant(dateFrom, InstantHelper.INSTANT_2000, true); Instant to = InstantHelper.findInstant(dateTo, Instant.now(), false); @@ -180,15 +194,12 @@ public ResponseEntity getValues(@QueryParam("from") String dateFrom, } @GetMapping(value = "instants/query") - @ApiOperation(value = "Retrieve values between date", - notes = "") - public ResponseEntity getValues(@QueryParam("from") String dateFrom, - @QueryParam("to") String dateTo, - @QueryParam("columns") String columns, - @QueryParam("intervalSeconds") long intervalSeconds, - @QueryParam("maxvalues") Integer maxValues) { - - maxValues = maxValues==null?100:maxValues; + @ApiOperation(value = "Retrieve values between date", notes = "") + public ResponseEntity getValues(@RequestParam(value = "from", required = false) String dateFrom, + @RequestParam(value = "to", required = false) String dateTo, + @RequestParam(value = "columns", required = false) String columns, + @RequestParam(value = "intervalSeconds", required = false) long intervalSeconds, + @RequestParam(value = "maxvalues", required = false, defaultValue = "100") Integer maxValues) { Instant from = InstantHelper.findInstant(dateFrom, InstantHelper.INSTANT_2000, true); Instant to = InstantHelper.findInstant(dateTo, Instant.now(), false); @@ -198,70 +209,64 @@ public ResponseEntity getValues(@QueryParam("from") String dateFrom, String ret = buildGson().toJson(values); return ResponseEntity.of(Optional.of(ret)); } catch (RuntimeException e) { - e.printStackTrace(); + LOG.error("Error", e); throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } } @GetMapping("stories") - @ApiOperation(value = "Retrieve all stories", - notes = "") + @ApiOperation(value = "Retrieve all stories", notes = "") public String getStories() { Gson gson = new GsonBuilder().registerTypeAdapter(StoryWEBDTO.class, new JsonStoryAdapter<>()).create(); List stories = getStoriesFacade().getStories(true).stream() - .map(s -> new StoryWEBDTO(s)) + .map(StoryWEBDTO::new) .collect(Collectors.toList()); return gson.toJson(stories); } @GetMapping(value = "story/{storyName}/run", produces = MediaType.TEXT_PLAIN) - @ApiOperation(value = "Ask to run a story", - notes = "Story is run before 3''") + @ApiOperation(value = "Ask to run a story", notes = "Story is run before 3''") public String getStoryRun(@PathVariable("storyName") String storyName) { daemon.runStory(storyName); return "Story " + storyName + " marked for execution"; } @GetMapping(value = "story/{storyName}/delete", produces = MediaType.TEXT_PLAIN) - @ApiOperation(value = "Delete story by name", - notes = "") + @ApiOperation(value = "Delete story by name", notes = "") public String getStoryDelete(@PathVariable("storyName") String storyName) { getStoriesFacade().deleteStory(storyName); return "Story " + storyName + " deleted."; } @GetMapping(value = "/story/{storyName}") - @ApiOperation(value = "Retrieve story by name", - notes = "") + @ApiOperation(value = "Retrieve story by name", notes = "") public String getStory(@PathVariable("storyName") String storyName) { Story story = getStoriesFacade().getStoryByName(storyName); if (story == null) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Sory " + storyName + " not found"); - } else { - Gson gson = new GsonBuilder().registerTypeAdapter(StoryWEBDTO.class, new JsonStoryAdapter()).create(); - return gson.toJson(new StoryWEBDTO(story)); } + Gson gson = new GsonBuilder().registerTypeAdapter(StoryWEBDTO.class, new JsonStoryAdapter<>()).create(); + return gson.toJson(new StoryWEBDTO(story)); } @GetMapping(value = "value/{valueName}", produces = MediaType.APPLICATION_JSON) - @ApiOperation(value = "Retrieve a single value", - notes = "") - public ResponseEntity getValue(@PathVariable("valueName") String valueName) { + @ApiOperation(value = "Retrieve a single value", notes = "") + public ResponseEntity getValue(@PathVariable("valueName") String valueName) { StoreValue storeValue = valuesStore.getValues().get(valueName); if (storeValue == null) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Value " + valueName + " not found"); } - return new ResponseEntity(storeValue.getValue(), HttpStatus.OK); + return new ResponseEntity<>(storeValue.getValue(), HttpStatus.OK); } @PostMapping(value = "value/{valueName}", produces = MediaType.APPLICATION_JSON) - public ResponseEntity postValue(@PathVariable("valueName") String valueName, @RequestBody String message) { + public ResponseEntity postValue(@PathVariable("valueName") String valueName, @RequestBody String message) { valuesStore.put(valueName, message); return getValue(valueName); } @@ -278,20 +283,17 @@ public String getOverview() { @GetMapping(value = "values/query/png", produces = MediaType.APPLICATION_OCTET_STREAM) @ApiOperation(value = "Retrieve values between date", notes = "(from null means from 2000, to null means now). Warning, retrieving many dates could be time-consuming and generate high volume of store") - public HttpEntity getValuesAsPNG(@QueryParam("from") String dateFrom, - @QueryParam("to") String dateTo, - @QueryParam("columns") String columns, - @QueryParam("ytitle") String yTitle, - @QueryParam("maxvalues") Integer maxValues, - @QueryParam("width") Integer width, - @QueryParam("height") Integer height, - HttpServletResponse response) { + public HttpEntity getValuesAsPNG(@RequestParam(value = "from", required = false) String dateFrom, + @RequestParam(value = "to", required = false) String dateTo, + @RequestParam(value = "columns", required = false) String columns, + @RequestParam(value = "ytitle", required = false) String yTitle, + @RequestParam(value = "maxvalues", required = false, defaultValue = "100") Integer maxValues, + @RequestParam(value = "width", required = false, defaultValue = "600") Integer width, + @RequestParam(value = "height", required = false, defaultValue = "400") Integer height, + HttpServletResponse response) { if (columns == null) { throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Missing 'columns'"); } - maxValues=maxValues==null?100:maxValues; - width=width==null?600:width; - height=height==null?400:height; Instant from = InstantHelper.findInstant(dateFrom, InstantHelper.INSTANT_2000, true); Instant to = InstantHelper.findInstant(dateTo, Instant.now(), false); @@ -307,9 +309,9 @@ public HttpEntity getValuesAsPNG(@QueryParam("from") String dateFrom, response.setContentType(org.springframework.http.MediaType.IMAGE_PNG_VALUE); StreamUtils.copy(png, response.getOutputStream()); - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity<>(HttpStatus.OK); } catch (RuntimeException | IOException e) { - e.printStackTrace(); + LOG.error("Error", e); throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } } diff --git a/src/main/java/ch/mno/copper/web/adapters/JsonStoryAdapter.java b/src/main/java/ch/mno/copper/web/adapters/JsonStoryAdapter.java index 5c20339..733b25c 100644 --- a/src/main/java/ch/mno/copper/web/adapters/JsonStoryAdapter.java +++ b/src/main/java/ch/mno/copper/web/adapters/JsonStoryAdapter.java @@ -1,15 +1,16 @@ package ch.mno.copper.web.adapters; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.web.dto.StoryWEBDTO; +import java.io.IOException; + import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; -import java.io.IOException; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.web.dto.StoryWEBDTO; public class JsonStoryAdapter extends TypeAdapter { - public StoryWEBDTO read(JsonReader reader) throws IOException { + public StoryWEBDTO read(JsonReader reader) { return null; } diff --git a/src/main/java/ch/mno/copper/web/filters/CORSFilter.java b/src/main/java/ch/mno/copper/web/filters/CORSFilter.java index 4f0312f..40f2bc8 100644 --- a/src/main/java/ch/mno/copper/web/filters/CORSFilter.java +++ b/src/main/java/ch/mno/copper/web/filters/CORSFilter.java @@ -1,11 +1,15 @@ package ch.mno.copper.web.filters; -import org.springframework.stereotype.Service; -import org.springframework.web.cors.CorsConfigurationSource; - -import javax.servlet.*; import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +import org.springframework.stereotype.Service; + @Service public class CORSFilter implements Filter { diff --git a/src/main/java/ch/mno/copper/web/filters/LoggingRequestFilter.java b/src/main/java/ch/mno/copper/web/filters/LoggingRequestFilter.java index e370623..09d3d3a 100644 --- a/src/main/java/ch/mno/copper/web/filters/LoggingRequestFilter.java +++ b/src/main/java/ch/mno/copper/web/filters/LoggingRequestFilter.java @@ -1,16 +1,14 @@ package ch.mno.copper.web.filters; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.filter.OncePerRequestFilter; - import javax.servlet.FilterChain; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.SecurityContext; -import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.filter.OncePerRequestFilter; public class LoggingRequestFilter extends OncePerRequestFilter { @@ -20,7 +18,7 @@ public class LoggingRequestFilter extends OncePerRequestFilter { private SecurityContext securityContext; @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) { // public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { if (securityContext != null) { String principal = securityContext.getUserPrincipal() == null ? "?" : securityContext.getUserPrincipal().getName(); diff --git a/src/main/java/ch/mno/copper/web/filters/RestrictedOperationsRequestFilter.java b/src/main/java/ch/mno/copper/web/filters/RestrictedOperationsRequestFilter.java index e9ce64b..3fbeed1 100644 --- a/src/main/java/ch/mno/copper/web/filters/RestrictedOperationsRequestFilter.java +++ b/src/main/java/ch/mno/copper/web/filters/RestrictedOperationsRequestFilter.java @@ -1,19 +1,11 @@ package ch.mno.copper.web.filters; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.Filter; import javax.servlet.FilterChain; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.*; import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.UUID; + +import org.springframework.web.filter.OncePerRequestFilter; // See https://simplapi.wordpress.com/2015/09/19/jersey-jax-rs-securitycontext-in-action/ @@ -23,7 +15,7 @@ @Provider public class RestrictedOperationsRequestFilter extends OncePerRequestFilter { @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) { } diff --git a/src/test/java/HttpTest.java b/src/test/java/HttpTest.java index 447a19b..5acf27b 100644 --- a/src/test/java/HttpTest.java +++ b/src/test/java/HttpTest.java @@ -1,6 +1,10 @@ -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.collect.connectors.HttpConnector; -import ch.mno.copper.report.PushoverReporter; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.apache.http.HttpHost; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; @@ -11,12 +15,7 @@ import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import ch.mno.copper.collect.connectors.ConnectorException; /** * Created by xsicdt on 17/02/16. @@ -31,7 +30,7 @@ public static String post(String uri, Map values) throws Connect HttpPost post = new HttpPost(uri); - final List nvps = new ArrayList(); + final List nvps = new ArrayList<>(); for (Map.Entry entry: values.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } diff --git a/src/test/java/Pushover.java b/src/test/java/Pushover.java index 0b4b1b7..5c06149 100644 --- a/src/test/java/Pushover.java +++ b/src/test/java/Pushover.java @@ -1,3 +1,4 @@ +import static java.nio.charset.StandardCharsets.UTF_8; import java.io.BufferedReader; import java.io.IOException; @@ -6,7 +7,6 @@ import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLEncoder; -import java.nio.charset.Charset; import javax.net.ssl.HttpsURLConnection; @@ -106,7 +106,8 @@ public void setDevice(String device) { * @throws IOException */ public String sendMessageHighPriority(String message, String title) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&title=" + URLEncoder.encode(title, "UTF-8") + "&priority=1"); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&title=" + URLEncoder.encode(title, + UTF_8) + "&priority=1"); } /** @@ -117,7 +118,7 @@ public String sendMessageHighPriority(String message, String title) throws Unsup * @throws IOException */ public String sendMessageHighPriority(String message) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&priority=1"); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&priority=1"); } /** @@ -131,8 +132,10 @@ public String sendMessageHighPriority(String message) throws UnsupportedEncoding * @throws IOException */ public String sendMessageHighPriority(String message, String title, String url, String urlTitle) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&title=" + URLEncoder.encode(title, "UTF-8") + "&url=" + URLEncoder.encode(url, "UTF-8") - + "&url_title=" + URLEncoder.encode(urlTitle, "UTF-8") + "&priority=1"); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&title=" + URLEncoder.encode(title, + UTF_8) + "&url=" + URLEncoder.encode(url, + UTF_8) + + "&url_title=" + URLEncoder.encode(urlTitle, UTF_8) + "&priority=1"); } /** @@ -145,7 +148,9 @@ public String sendMessageHighPriority(String message, String title, String url, * @throws IOException */ public String sendMessageHighPriority(String message, String title, String url) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&title=" + URLEncoder.encode(title, "UTF-8") + "&url=" + URLEncoder.encode(url, "UTF-8") + "&priority=1"); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&title=" + URLEncoder.encode(title, + UTF_8) + "&url=" + URLEncoder.encode(url, + UTF_8) + "&priority=1"); } /** @@ -159,8 +164,10 @@ public String sendMessageHighPriority(String message, String title, String url) * @throws IOException */ public String sendMessage(String message, String title, String url, String urlTitle) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&title=" + URLEncoder.encode(title, "UTF-8") + "&url=" + URLEncoder.encode(url, "UTF-8") - + "&url_title=" + URLEncoder.encode(urlTitle, "UTF-8")); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&title=" + URLEncoder.encode(title, + UTF_8) + "&url=" + URLEncoder.encode(url, + UTF_8) + + "&url_title=" + URLEncoder.encode(urlTitle, UTF_8)); } /** @@ -173,7 +180,9 @@ public String sendMessage(String message, String title, String url, String urlTi * @throws IOException */ public String sendMessage(String message, String title, String url) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&title=" + URLEncoder.encode(title, "UTF-8") + "&url=" + URLEncoder.encode(url, "UTF-8")); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&title=" + URLEncoder.encode(title, + UTF_8) + "&url=" + URLEncoder.encode(url, + UTF_8)); } /** @@ -185,7 +194,8 @@ public String sendMessage(String message, String title, String url) throws Unsup * @throws IOException */ public String sendMessage(String message, String title) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8") + "&title=" + URLEncoder.encode(title, "UTF-8")); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8) + "&title=" + URLEncoder.encode(title, + UTF_8)); } /** @@ -196,18 +206,17 @@ public String sendMessage(String message, String title) throws UnsupportedEncodi * @throws IOException */ public String sendMessage(String message) throws UnsupportedEncodingException, IOException { - return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, "UTF-8")); + return sendToPushoverRaw(getAuthenticationTokens() + "&message=" + URLEncoder.encode(message, UTF_8)); } /** * Gets a string with the auth tokens already made. * @return String of auth tokens - * @throws UnsupportedEncodingException */ - private String getAuthenticationTokens() throws UnsupportedEncodingException{ + private String getAuthenticationTokens() { if (device != null) { - if (!(device.trim() == "")) { + if (!(device.trim().equals(""))) { return "token=" + getAppToken() + "&user=" + getUserToken() + "&device=" + getDevice(); } } @@ -229,18 +238,18 @@ private String sendToPushoverRaw(String rawMessage) throws IOException { connection.setDoInput(true); OutputStream outputStream = connection.getOutputStream(); - outputStream.write(rawMessage.getBytes(Charset.forName("UTF-8"))); + outputStream.write(rawMessage.getBytes(UTF_8)); outputStream.close(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); - String output = ""; + StringBuilder output = new StringBuilder(); String outputCache = ""; while ((outputCache = br.readLine()) != null) { - output += outputCache; + output.append(outputCache); } br.close(); - return output; + return output.toString(); } public static void main(String[] args) throws IOException { diff --git a/src/test/java/SandboxMain.java b/src/test/java/SandboxMain.java index 2745863..e15e7cd 100644 --- a/src/test/java/SandboxMain.java +++ b/src/test/java/SandboxMain.java @@ -1,14 +1,15 @@ import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; /** * Created by xsicdt on 07/11/17. */ public class SandboxMain { - public static String convert(String s) throws UnsupportedEncodingException { - byte[] bytes = s.getBytes("UTF-8"); - for (int i=0; i lstCollectors = Arrays.asList(coll1); -// List lstProcessors = Arrays.asList(proc1, proc2); -// DataProvider dataProvider = new DataProvider() { -// @Override -// public Set> getStoryTasks() { -// ()->lstCollectors; -// } -// -// @Override -// public List getStories() { -// return null; -// } -// -// @Override -// public StoryTask getStoryTask(Story story) { -// return null; -// } -// } -// CopperDaemon daemon = CopperDaemon.runWith(dataProvider); -// int nb=0; -// while (coll1.nbRuns==0 && nb++<20) { -// Thread.sleep(CopperDaemon.TASK_CHEK_INTERVAL / 4); -// } -// Assert.assertEquals("Check1", 1, coll1.nbRuns); -// Assert.assertEquals("Check2", 1, coll1.nbMark); -// nb=0; -// while (coll1.nbRuns==1 && nb++<20) { -// Thread.sleep(CopperDaemon.TASK_CHEK_INTERVAL / 4); -// } -// Assert.assertEquals("Check3", 2, coll1.nbRuns); -// Assert.assertEquals("Check4", 2, coll1.nbMark); -// -// // Test processors -// Assert.assertEquals("Check5", 0, proc1.nbTrig); -// Assert.assertEquals("Check6", 0, proc2.nbTrig); -// valueStore.put("key1", "value1"); -// nb=0; -// while (proc1.nbTrig==0 && nb++<400) { -//// System.out.println(nb+" sleeping " + CopperDaemon.TASK_CHEK_INTERVAL / 4); -// Thread.sleep(CopperDaemon.TASK_CHEK_INTERVAL / 4); -// } -// Assert.assertEquals("Check7-nb=" + nb, 1, proc1.nbTrig); -// Assert.assertEquals("Check8", 0, proc2.nbTrig); -// valueStore.put("key2", "value2"); -// nb=0; -// while (proc2.nbTrig==0 && nb++<20) { -// Thread.sleep(CopperDaemon.TASK_CHEK_INTERVAL / 4); -// } -// Assert.assertEquals("Check9", 1, proc1.nbTrig); -// Assert.assertEquals("Check10", 1, proc2.nbTrig); -// -// daemon.stop(); -// Thread.sleep(CopperDaemon.TASK_CHEK_INTERVAL+100); -// } - - private static class SimpleStoryTask implements StoryTask { - int nbRuns=0; - int nbMark = 0; - - @Override - public String storyName() { - return "aName"; - } - - @Override - public String getTitle() { - return "aTitle"; - } - - @Override - public long getTaskId() { - return 42; - } - - @Override - public Runnable getRunnable() { - return new Runnable() { - @Override - public void run() { - nbRuns++; - } - }; - } - - @Override - public boolean shouldRun() { - return true; - } - - @Override - public long getNextRun() { - return 0; - } - - @Override - public void markAsRun() { - nbMark++; - } - - @Override - public void markAsRunning() { - - } - } - - private static class SimpleProcessor extends AbstractProcessor { - - int nbTrig=0; - - public SimpleProcessor(List valuesTrigger) { - super(valuesTrigger); - } - - @Override - public void trig(ValuesStore valueStore, Collection changedValueKeys) { - nbTrig++; - } - } - -} diff --git a/src/test/java/ch/mno/copper/CopperTestHelper.java b/src/test/java/ch/mno/copper/CopperTestHelper.java deleted file mode 100644 index bfb3353..0000000 --- a/src/test/java/ch/mno/copper/CopperTestHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -package ch.mno.copper; - -import java.io.IOException; -import java.net.ServerSocket; - -public class CopperTestHelper { - - // https://gist.github.com/vorburger/3429822 - public static int findFreePort() { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); - socket.setReuseAddress(true); - int port = socket.getLocalPort(); - try { - socket.close(); - } catch (IOException e) { - // Ignore IOException on close() - } - return port; - } catch (IOException e) { - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } - } - } - throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on"); - } - -} diff --git a/src/test/java/ch/mno/copper/DataProviderTest.java b/src/test/java/ch/mno/copper/DataProviderTest.java index cca1051..c763bb5 100644 --- a/src/test/java/ch/mno/copper/DataProviderTest.java +++ b/src/test/java/ch/mno/copper/DataProviderTest.java @@ -1,5 +1,15 @@ package ch.mno.copper; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + import ch.mno.copper.collect.StoryTask; import ch.mno.copper.collect.connectors.ConnectorException; import ch.mno.copper.store.MapValuesStore; @@ -8,16 +18,6 @@ import ch.mno.copper.stories.data.Story; import ch.mno.copper.stories.data.StoryGrammar; import ch.mno.copper.stories.data.StoryValidationResult; -import org.junit.Assert; -import org.junit.Test; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; public class DataProviderTest { @@ -52,7 +52,7 @@ public void testAfterNewStory() throws IOException, ConnectorException { } - private class StoriesFacadeMock implements StoriesFacade { + private static class StoriesFacadeMock implements StoriesFacade { Map stories = new HashMap<>(); @@ -67,7 +67,7 @@ public List getStories(boolean shouldRefreshFromDisk) { } @Override - public Story buildStory(FileInputStream fileInputStream, String storyName) throws IOException, ConnectorException { + public Story buildStory(FileInputStream fileInputStream, String storyName) { return null; } @@ -77,12 +77,12 @@ public StoryTask buildStoryTask(Story story, ValuesStore valuesStore) { } @Override - public String saveNewStory(String storyName, String storyText) throws IOException, ConnectorException { + public String saveNewStory(String storyName, String storyText) { return null; } @Override - public String updateStory(String originalStoryName, String storyName, String storyText) throws IOException, ConnectorException { + public String updateStory(String originalStoryName, String storyName, String storyText) { return null; } diff --git a/src/test/java/ch/mno/copper/LocalTestDSI.java b/src/test/java/ch/mno/copper/LocalTestDSI.java index 4d9e62b..e6a1054 100644 --- a/src/test/java/ch/mno/copper/LocalTestDSI.java +++ b/src/test/java/ch/mno/copper/LocalTestDSI.java @@ -1,7 +1,5 @@ package ch.mno.copper; -import ch.mno.copper.collect.connectors.ConnectorException; - import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; @@ -12,7 +10,7 @@ */ public class LocalTestDSI { - public static void main(String[] args) throws ConnectorException { + public static void main(String[] args) { /* Map values = new HashMap<>(); values.put(MailReporter.PARAMETERS.TO.toString(), "cedric.dutoit@vd.ch"); values.put(MailReporter.PARAMETERS.TITLE.toString(), "RCFACE Copper test"); @@ -186,7 +184,7 @@ private static String convertDefaultNamespaceToPrefixed(String xml2) { if (tag.charAt(0)=='/') { // Closing tag prefix = prefixByLevels.get(noLevel); - sb.append(""); + sb.append(""); noLevel--; } else { noLevel++; @@ -205,7 +203,7 @@ private static String convertDefaultNamespaceToPrefixed(String xml2) { } } prefixByLevels.put(noLevel, prefix); // (also copy default if not found) - sb.append("<"+prefix +":" + tag + ">"); + sb.append("<").append(prefix).append(":").append(tag).append(">"); if (tag.endsWith("/")) noLevel--; } } else if (inTag) { diff --git a/src/test/java/ch/mno/copper/Sandbox.java b/src/test/java/ch/mno/copper/Sandbox.java index 5d87ea2..1e772c7 100644 --- a/src/test/java/ch/mno/copper/Sandbox.java +++ b/src/test/java/ch/mno/copper/Sandbox.java @@ -1,18 +1,12 @@ package ch.mno.copper; -import ch.mno.copper.collect.WebCollector; -import ch.mno.copper.collect.WebCollectorWrapper; +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.format.DateTimeFormatter; -import java.time.temporal.TemporalAccessor; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import ch.mno.copper.collect.WebCollector; /** * Created by xsicdt on 26/07/16. diff --git a/src/test/java/ch/mno/copper/collect/BinaryCollectorTest.java b/src/test/java/ch/mno/copper/collect/BinaryCollectorTest.java index 7f58a1b..23a0b2e 100644 --- a/src/test/java/ch/mno/copper/collect/BinaryCollectorTest.java +++ b/src/test/java/ch/mno/copper/collect/BinaryCollectorTest.java @@ -1,14 +1,14 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; +import java.io.File; +import java.io.IOException; + import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.File; -import java.io.IOException; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; public class BinaryCollectorTest { @@ -16,13 +16,13 @@ public class BinaryCollectorTest { private StoryGrammar storyGrammar; @Before - public void setup() throws IOException { + public void setup() { storyGrammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } @Test - public void testCheckByPathOnInexistant() throws ConnectorException { + public void testCheckByPathOnInexistant() { BinaryCollectorWrapper collector = BinaryCollectorWrapper.buildCollector(storyGrammar, "BINARY_CHECK\nCHECK_BY_PATH dummy AS DUMMY_AVAILABLE\n"); Assert.assertEquals("DUMMY_AVAILABLE", collector.getAs().get(0)); @@ -31,7 +31,7 @@ public void testCheckByPathOnInexistant() throws ConnectorException { } @Test - public void testCheckByPathOnExistant() throws ConnectorException, IOException { + public void testCheckByPathOnExistant() throws IOException { File f = File.createTempFile("dummy","tmp"); f.deleteOnExit(); BinaryCollectorWrapper collector = BinaryCollectorWrapper.buildCollector(storyGrammar, @@ -42,7 +42,7 @@ public void testCheckByPathOnExistant() throws ConnectorException, IOException { } @Test - public void testWhichOnInexistant() throws ConnectorException { + public void testWhichOnInexistant() { BinaryCollectorWrapper collector = BinaryCollectorWrapper.buildCollector(storyGrammar, "BINARY_CHECK\nCHECK_BY_WHICH dummy123 AS DUMMY_AVAILABLE\n"); Assert.assertEquals("DUMMY_AVAILABLE", collector.getAs().get(0)); @@ -51,7 +51,7 @@ public void testWhichOnInexistant() throws ConnectorException { } @Test - public void testWhichOnExistant() throws ConnectorException { + public void testWhichOnExistant() { BinaryCollectorWrapper collector = BinaryCollectorWrapper.buildCollector(storyGrammar, "BINARY_CHECK\nCHECK_BY_WHICH ls AS DUMMY_AVAILABLE\n"); Assert.assertEquals("DUMMY_AVAILABLE", collector.getAs().get(0)); diff --git a/src/test/java/ch/mno/copper/collect/JmxCollectorWrapperTest.java b/src/test/java/ch/mno/copper/collect/JmxCollectorWrapperTest.java index 8689a15..d5f3d98 100644 --- a/src/test/java/ch/mno/copper/collect/JmxCollectorWrapperTest.java +++ b/src/test/java/ch/mno/copper/collect/JmxCollectorWrapperTest.java @@ -1,13 +1,12 @@ package ch.mno.copper.collect; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.FileNotFoundException; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; /** * Created by xsicdt on 29/02/16. @@ -17,7 +16,7 @@ public class JmxCollectorWrapperTest { private StoryGrammar storyGrammar; @Before - public void init() throws FileNotFoundException { + public void init() { storyGrammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } diff --git a/src/test/java/ch/mno/copper/collect/SocketCollectorTest.java b/src/test/java/ch/mno/copper/collect/SocketCollectorTest.java index bf0d687..8d64dd3 100644 --- a/src/test/java/ch/mno/copper/collect/SocketCollectorTest.java +++ b/src/test/java/ch/mno/copper/collect/SocketCollectorTest.java @@ -1,16 +1,14 @@ package ch.mno.copper.collect; -import ch.mno.copper.AbstractJmxServerTestStarter; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; -import ch.mno.copper.test.WebServer4Tests; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.io.IOException; +import ch.mno.copper.AbstractJmxServerTestStarter; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; +import ch.mno.copper.test.WebServer4Tests; /** @@ -24,7 +22,7 @@ public class SocketCollectorTest extends AbstractJmxServerTestStarter { private static StoryGrammar storyGrammar; @BeforeClass - public static void setup() throws IOException { + public static void setup() { storyGrammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); // HTTP Server ws = new WebServer4Tests(HTTP_PORT); @@ -37,7 +35,7 @@ public static void done() throws Exception { } @Test - public void testCheckConnectionOnDummyServer() throws ConnectorException { + public void testCheckConnectionOnDummyServer() { SocketCollectorWrapper collector = SocketCollectorWrapper.buildCollector(storyGrammar, "SOCKET WITH host=localhost,port=1,timeout_ms=1000\nKEEP status AS myStatus\n"); Assert.assertEquals("myStatus", collector.getAs().get(0)); Assert.assertEquals("IO_EXCEPTION", collector.execute2D().get(0).get(0)); @@ -45,14 +43,14 @@ public void testCheckConnectionOnDummyServer() throws ConnectorException { } @Test - public void testCheckConnectionOnRealServerJMX() throws ConnectorException { + public void testCheckConnectionOnRealServerJMX() { SocketCollectorWrapper collector = SocketCollectorWrapper.buildCollector(storyGrammar, "SOCKET WITH host=localhost,port=" + JMX_PORT + ",timeout_ms=1000\nKEEP status AS myStatus\n"); Assert.assertEquals("OK", collector.execute2D().get(0).get(0)); Assert.assertEquals("OK", collector.execute().get("myStatus")); } @Test - public void testCheckConnectionOnRealServerHTTP() throws ConnectorException { + public void testCheckConnectionOnRealServerHTTP() { try ( // HTTP Server WebServer4Tests ws = new WebServer4Tests(HTTP_PORT); diff --git a/src/test/java/ch/mno/copper/collect/StoryTaskTest.java b/src/test/java/ch/mno/copper/collect/StoryTaskTest.java index 968a07a..1c02488 100644 --- a/src/test/java/ch/mno/copper/collect/StoryTaskTest.java +++ b/src/test/java/ch/mno/copper/collect/StoryTaskTest.java @@ -1,19 +1,22 @@ package ch.mno.copper.collect; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + import ch.mno.copper.collect.connectors.ConnectorException; import ch.mno.copper.store.MapValuesStore; import ch.mno.copper.store.ValuesStore; import ch.mno.copper.stories.StoryTaskBuilder; import ch.mno.copper.stories.data.Story; import ch.mno.copper.stories.data.StoryGrammar; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mockito; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.*; /** * Created by dutoitc on 16.02.2016. @@ -24,21 +27,21 @@ public class StoryTaskTest { private static StoryGrammar grammar; @BeforeClass - public static void init() throws FileNotFoundException { + public static void init() { grammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } @Test public void testCronMinute() { - List values = new ArrayList(); + List values = new ArrayList<>(); StoryTask ct = new StoryTaskImpl(null, ()->values.add("1"), "* * * * *"); Assert.assertTrue(Math.abs(ct.getNextRun()-System.currentTimeMillis())<=60000); } @Test public void testCronMinute2() { - List values = new ArrayList(); + List values = new ArrayList<>(); StoryTask ct = new StoryTaskImpl(null, ()->values.add("1"), "0 * * * *"); Assert.assertTrue(Math.abs(ct.getNextRun()-System.currentTimeMillis())<=60*60*1000); } @@ -48,15 +51,15 @@ public void testBuildAndRunOk() throws IOException, ConnectorException { Story story = new Story(grammar, "StoryName", "RUN ON CRON 0 8,13 * * *\nGIVEN STORED VALUES\nTHEN\nSTORE VALUES"); story.setCollectorWrapper4Tests(new AbstractCollectorWrapper() { @Override - public Map execute() throws ConnectorException { - Map map = new HashMap(); + public Map execute() { + Map map = new HashMap<>(); map.put("KEY1", "VALUE1"); map.put("KEY2", "VALUE2"); return map; } @Override - public List> execute2D() throws ConnectorException { + public List> execute2D() { return null; } }); @@ -79,7 +82,7 @@ public Map execute() throws ConnectorException { } @Override - public List> execute2D() throws ConnectorException { + public List> execute2D() { return null; } @@ -111,7 +114,7 @@ public Map execute() throws ConnectorException { } @Override - public List> execute2D() throws ConnectorException { + public List> execute2D() { return null; } diff --git a/src/test/java/ch/mno/copper/collect/WebCollectorTest.java b/src/test/java/ch/mno/copper/collect/WebCollectorTest.java index cb13d2b..167539b 100644 --- a/src/test/java/ch/mno/copper/collect/WebCollectorTest.java +++ b/src/test/java/ch/mno/copper/collect/WebCollectorTest.java @@ -1,13 +1,14 @@ package ch.mno.copper.collect; -import ch.mno.copper.collect.connectors.HttpResponseData; +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.junit.Assert; import org.junit.Test; -import java.util.ArrayList; -import java.util.List; +import ch.mno.copper.collect.connectors.HttpResponseData; /** * Created by xsicdt on 25/08/17. @@ -138,9 +139,9 @@ public void testRegexp() { "}}}"; List> valuesKept = new ArrayList<>(); - valuesKept.add(new ImmutablePair("regexp:WS_Chose_V3.(?\\d+\\.\\d+\\.\\d+)", "value")); + valuesKept.add(new ImmutablePair<>("regexp:WS_Chose_V3.(?\\d+\\.\\d+\\.\\d+)", "value")); //valuesKept.add(new ImmutablePair("$..*[?(@.Name=='WS_Chose_V3')].Version", "value2")); - valuesKept.add(new ImmutablePair("regexp:WS_Bidule_V3..?(?\\[123]d\\.\\d+\\.\\d+)", "value3")); + valuesKept.add(new ImmutablePair<>("regexp:WS_Bidule_V3..?(?\\[123]d\\.\\d+\\.\\d+)", "value3")); diff --git a/src/test/java/ch/mno/copper/collect/WebCollectorWrapperTest.java b/src/test/java/ch/mno/copper/collect/WebCollectorWrapperTest.java index db91700..d6d579e 100644 --- a/src/test/java/ch/mno/copper/collect/WebCollectorWrapperTest.java +++ b/src/test/java/ch/mno/copper/collect/WebCollectorWrapperTest.java @@ -1,15 +1,16 @@ package ch.mno.copper.collect; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; -import com.jayway.jsonpath.JsonPath; +import java.util.Map; + import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.io.FileNotFoundException; -import java.util.Map; +import com.jayway.jsonpath.JsonPath; + +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; /** * Created by xsicdt on 29/02/16. @@ -19,7 +20,7 @@ public class WebCollectorWrapperTest { private StoryGrammar storyGrammar; @Before - public void init() throws FileNotFoundException { + public void init() { storyGrammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } @@ -52,7 +53,7 @@ public void test() { @Test - public void test2() throws Exception { + public void test2() { String jmx = "GIVEN COLLECTOR WEB WITH url=http://hostname:8040/jolokia/exec/org.apache.karaf:type=bundles,name=trun/list\n" + " KEEP $.value[?(/value.WS_Services$/.test(@.Name))].Version AS value_VERSION\n" + "THEN STORE VALUES"; diff --git a/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTest.java b/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTest.java index 58a9478..8384576 100644 --- a/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTest.java +++ b/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTest.java @@ -1,19 +1,12 @@ package ch.mno.copper.collect.connectors; -import ch.mno.copper.AbstractWebPortSpringTest; -import ch.mno.copper.CopperApplication; +import java.util.HashMap; +import java.util.Map; + import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.context.annotation.Import; -import org.springframework.test.context.junit4.SpringRunner; -import java.util.HashMap; -import java.util.Map; +import ch.mno.copper.AbstractWebPortSpringTest; public class HttpConnectorTest extends AbstractWebPortSpringTest { @@ -26,7 +19,7 @@ public void ping1() throws Exception { } @Test - public void test2() throws ConnectorException { + public void test2() { // Port non ouvert + 10 try (HttpConnector conn = new HttpConnector("localhost", port + 10, "http")) { String res = conn.get("/something"); diff --git a/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTestController.java b/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTestController.java index 8a645b9..cc050f9 100644 --- a/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTestController.java +++ b/src/test/java/ch/mno/copper/collect/connectors/HttpConnectorTestController.java @@ -1,15 +1,15 @@ package ch.mno.copper.collect.connectors; +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.commons.io.IOUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.PrintWriter; - @RestController public class HttpConnectorTestController { diff --git a/src/test/java/ch/mno/copper/collect/connectors/JmxConnectorTest.java b/src/test/java/ch/mno/copper/collect/connectors/JmxConnectorTest.java index 2d9d0c9..c980f04 100644 --- a/src/test/java/ch/mno/copper/collect/connectors/JmxConnectorTest.java +++ b/src/test/java/ch/mno/copper/collect/connectors/JmxConnectorTest.java @@ -1,11 +1,17 @@ package ch.mno.copper.collect.connectors; -import ch.mno.copper.AbstractJmxServerTestStarter; +import java.io.IOException; + +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ReflectionException; + import org.junit.Assert; import org.junit.Test; -import javax.management.*; -import java.io.IOException; +import ch.mno.copper.AbstractJmxServerTestStarter; /** * Created by dutoitc on 15.02.2016. @@ -13,7 +19,7 @@ public class JmxConnectorTest extends AbstractJmxServerTestStarter { @Test - public void testX() throws IOException, MalformedObjectNameException, AttributeNotFoundException, MBeanException, ReflectionException, InstanceNotFoundException, InterruptedException { + public void testX() throws IOException, MalformedObjectNameException, AttributeNotFoundException, MBeanException, ReflectionException, InstanceNotFoundException { JmxConnector conn = new JmxConnector("service:jmx:rmi:///jndi/rmi://localhost:"+JMX_PORT+"/server"); String aValue = conn.getObject("java.lang:type=Runtime", "SpecName"); Assert.assertTrue(aValue.contains("Java")); diff --git a/src/test/java/ch/mno/copper/collect/connectors/SocketConnectorTest.java b/src/test/java/ch/mno/copper/collect/connectors/SocketConnectorTest.java index 5c837a3..ccd84ad 100644 --- a/src/test/java/ch/mno/copper/collect/connectors/SocketConnectorTest.java +++ b/src/test/java/ch/mno/copper/collect/connectors/SocketConnectorTest.java @@ -1,13 +1,12 @@ package ch.mno.copper.collect.connectors; -import ch.mno.copper.AbstractJmxServerTestStarter; -import ch.mno.copper.test.WebServer4Tests; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.io.IOException; +import ch.mno.copper.AbstractJmxServerTestStarter; +import ch.mno.copper.test.WebServer4Tests; public class SocketConnectorTest extends AbstractJmxServerTestStarter { @@ -15,7 +14,7 @@ public class SocketConnectorTest extends AbstractJmxServerTestStarter { private static WebServer4Tests ws; @BeforeClass - public static void setup() throws IOException, InterruptedException { + public static void setup() throws InterruptedException { // HTTP Server ws = new WebServer4Tests(HTTP_PORT); ws.start(); diff --git a/src/test/java/ch/mno/copper/report/CsvReporterTest.java b/src/test/java/ch/mno/copper/report/CsvReporterTest.java index 9b4757e..aa1a1d4 100644 --- a/src/test/java/ch/mno/copper/report/CsvReporterTest.java +++ b/src/test/java/ch/mno/copper/report/CsvReporterTest.java @@ -1,30 +1,29 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Test; - import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Test; + /** * Created by dutoitc on 26.04.2019. */ public class CsvReporterTest { @Test - public void testOne() throws IOException, ConnectorException { + public void testOne() throws IOException { // New file File file = File.createTempFile("copper", "tmp"); file.delete(); file.deleteOnExit(); // Some values - Map values = new HashMap(); + Map values = new HashMap<>(); values.put(CsvReporter.PARAMETERS.FILENAME.name(), file.getAbsolutePath()); values.put(CsvReporter.PARAMETERS.HEADERS.name(), "value1;value2;value3"); values.put(CsvReporter.PARAMETERS.LINE.name(), "aValue;anotherValue;lastValue"); @@ -36,7 +35,7 @@ public void testOne() throws IOException, ConnectorException { Assert.assertEquals("value1;value2;value3\r\naValue;anotherValue;lastValue\r\n", res); // More values - values = new HashMap(); + values = new HashMap<>(); values.put(CsvReporter.PARAMETERS.FILENAME.name(), file.getAbsolutePath()); values.put(CsvReporter.PARAMETERS.HEADERS.name(), "value1;value2;value3"); values.put(CsvReporter.PARAMETERS.LINE.name(), "123;456;789"); diff --git a/src/test/java/ch/mno/copper/report/CsvReporterWrapperTest.java b/src/test/java/ch/mno/copper/report/CsvReporterWrapperTest.java index 3f6fb4d..ac2b350 100644 --- a/src/test/java/ch/mno/copper/report/CsvReporterWrapperTest.java +++ b/src/test/java/ch/mno/copper/report/CsvReporterWrapperTest.java @@ -1,22 +1,23 @@ package ch.mno.copper.report; -import ch.mno.copper.store.MapValuesStore; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; import config.CopperMailProperties; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.Map; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ch.mno.copper.store.MapValuesStore; +import ch.mno.copper.store.ValuesStore; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; + /** * Created by dutoitc on 26.04.2019. */ @@ -25,7 +26,7 @@ public class CsvReporterWrapperTest { private StoryGrammar storyGrammar; @Before - public void init() throws FileNotFoundException { + public void init() { storyGrammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } @@ -46,7 +47,7 @@ public void test() throws IOException { CsvReporterWrapper wrapper = new ReporterWrapperFactory(props).buildReporterWrapper(storyGrammar, story); // Run - Map values = new HashMap(); + Map values = new HashMap<>(); values.put("value1", "123"); values.put("value2", "456"); values.put("value3", "789"); @@ -57,7 +58,7 @@ public void test() throws IOException { Assert.assertEquals("my header1;my header2;my header3\r\n123;456;789\r\n", res); // Run - values = new HashMap(); + values = new HashMap<>(); values.put("value1", "aaa"); values.put("value3", "ccc"); wrapper.execute(values, valuesStore); diff --git a/src/test/java/ch/mno/copper/report/MailReporterTest.java b/src/test/java/ch/mno/copper/report/MailReporterTest.java index 9ace56b..da4928f 100644 --- a/src/test/java/ch/mno/copper/report/MailReporterTest.java +++ b/src/test/java/ch/mno/copper/report/MailReporterTest.java @@ -1,26 +1,26 @@ package ch.mno.copper.report; -import ch.mno.copper.collect.connectors.ConnectorException; -import org.apache.commons.mail.EmailException; -import org.apache.commons.mail.HtmlEmail; -import org.junit.Assert; -import org.junit.Test; - -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; + +import org.apache.commons.mail.HtmlEmail; +import org.junit.Assert; +import org.junit.Test; + /** * Created by dutoitc on 26.04.2019. */ public class MailReporterTest { @Test - public void testAll() throws ConnectorException, MessagingException, IOException { - MailReporter reporter = new TestableMailReporter("dummyServer", "aUser", "aPass", 6666, "from@dummy.xxx", "to@dummy.xxx" ); + public void testAll() throws MessagingException, IOException { + MailReporter reporter = new TestableMailReporter("dummyServer", "aUser", "aPass", 6666, "from@dummy.xxx", "to@dummy.xxx"); Map values = new HashMap<>(); values.put(MailReporter.PARAMETERS.TO.name(), "to2@dummy.xxx"); values.put(MailReporter.PARAMETERS.TITLE.name(), "aTitle"); @@ -29,7 +29,7 @@ public void testAll() throws ConnectorException, MessagingException, IOException ByteArrayOutputStream os = new ByteArrayOutputStream(); TestableHtmlEmail.data.writeTo(os); - String mail = new String(os.toByteArray(), "UTF-8"); + String mail = new String(os.toByteArray(), StandardCharsets.UTF_8); System.out.println(mail); Assert.assertTrue(mail.contains("From: from@dummy.xxx")); Assert.assertTrue(mail.contains("Reply-To: to@dummy.xxx")); @@ -42,13 +42,13 @@ private static class TestableHtmlEmail extends HtmlEmail { private static MimeMessage data; - public String sendMimeMessage() throws EmailException { + public String sendMimeMessage() { this.data = this.getMimeMessage(); return null; } } - private class TestableMailReporter extends MailReporter { + private static class TestableMailReporter extends MailReporter { /* HtmlEmail mock = Mockito.mock(HtmlEmail.class); { diff --git a/src/test/java/ch/mno/copper/store/db/DBServerManual.java b/src/test/java/ch/mno/copper/store/db/DBServerManual.java index eaa4dad..93088ec 100644 --- a/src/test/java/ch/mno/copper/store/db/DBServerManual.java +++ b/src/test/java/ch/mno/copper/store/db/DBServerManual.java @@ -1,10 +1,5 @@ package ch.mno.copper.store.db; -import org.h2.jdbcx.JdbcConnectionPool; -import org.h2.tools.Server; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -12,6 +7,11 @@ import java.util.ArrayList; import java.util.List; +import org.h2.jdbcx.JdbcConnectionPool; +import org.h2.tools.Server; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + public class DBServerManual extends DBServer implements AutoCloseable { private static Logger LOG = LoggerFactory.getLogger(DBServerManual.class); static String DBURL = "jdbc:h2:./copperdb"; // static for tests @@ -75,7 +75,7 @@ public void close() throws Exception { Thread.sleep(100); } - private void createDatabaseIfNeeded() throws SQLException { + private void createDatabaseIfNeeded() { LOG.info("Checking Database..."); try (Connection con = cp.getConnection(); Statement stmt = con.createStatement()) { @@ -111,7 +111,7 @@ private void createDatabaseIfNeeded() throws SQLException { LOG.info("Database checked"); } - private void fixSnapshots() throws SQLException { + private void fixSnapshots() { LOG.info("Checking Database..."); try (Connection con = cp.getConnection(); Statement stmt = con.createStatement()) { diff --git a/src/test/java/ch/mno/copper/store/db/DBServerTest.java b/src/test/java/ch/mno/copper/store/db/DBServerTest.java index 84bdb2f..26c953f 100644 --- a/src/test/java/ch/mno/copper/store/db/DBServerTest.java +++ b/src/test/java/ch/mno/copper/store/db/DBServerTest.java @@ -1,17 +1,21 @@ package ch.mno.copper.store.db; -import ch.mno.copper.CopperApplication; -import ch.mno.copper.store.StoreValue; +import java.time.Instant; +import java.util.List; + import org.apache.commons.lang3.StringUtils; -import org.junit.*; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import java.sql.SQLException; -import java.time.Instant; -import java.util.List; +import ch.mno.copper.CopperApplication; +import ch.mno.copper.store.StoreValue; @RunWith(SpringRunner.class) @SpringBootTest(classes = { @@ -36,7 +40,7 @@ public static void beforeClass() { private DBServer server; @Before - public void init() throws SQLException { + public void init() { server.clearAllData(); server.insert("key1", "value10", i5); server.insert("key2", "value20", i5); @@ -48,27 +52,27 @@ public void init() throws SQLException { } @Test - public void testReadLatestForOneValue() throws SQLException { + public void testReadLatestForOneValue() { StoreValue readSV = server.readLatest("key1"); Assert.assertEquals("value10", readSV.getValue()); } @Test - public void testReadLatestForTwoValues() throws SQLException { + public void testReadLatestForTwoValues() { StoreValue readSV = server.readLatest("key3"); Assert.assertEquals("value31", readSV.getValue()); } @Test - public void testReadLatestForThreeValues() throws SQLException { + public void testReadLatestForThreeValues() { StoreValue readSV = server.readLatest("key4"); Assert.assertEquals("value42", readSV.getValue()); } @Test - public void testReadAtTimestampForOneValue() throws SQLException { + public void testReadAtTimestampForOneValue() { Assert.assertNull(server.read("key1", i3)); Assert.assertNull(server.read("key1", i4)); Assert.assertEquals("value10", server.read("key1", i5).getValue()); @@ -79,7 +83,7 @@ public void testReadAtTimestampForOneValue() throws SQLException { } @Test - public void testReadAtTimestampForTwoValues() throws SQLException { + public void testReadAtTimestampForTwoValues() { Assert.assertNull(server.read("key3", i3)); Assert.assertEquals("value30", server.read("key3", i4).getValue()); Assert.assertEquals("value30", server.read("key3", i5).getValue()); @@ -90,7 +94,7 @@ public void testReadAtTimestampForTwoValues() throws SQLException { } @Test - public void testReadAtTimestampForThreeValues() throws SQLException { + public void testReadAtTimestampForThreeValues() { Assert.assertNull(server.read("key4", i3)); Assert.assertEquals("value40", server.read("key4", i4).getValue()); Assert.assertEquals("value41", server.read("key4", i5).getValue()); @@ -101,7 +105,7 @@ public void testReadAtTimestampForThreeValues() throws SQLException { } @Test - public void testReadHistorizedForOneValue() throws SQLException { + public void testReadHistorizedForOneValue() { Assert.assertTrue(server.read("key1", i3, i4, 100).isEmpty()); Assert.assertTrue(server.read("key1", i4, i5, 100).isEmpty()); assertOneValue(server.read("key1", i5, i6, 100), "value10"); @@ -111,7 +115,7 @@ public void testReadHistorizedForOneValue() throws SQLException { } @Test - public void testReadHistorizedForTwoValues() throws SQLException { + public void testReadHistorizedForTwoValues() { Assert.assertTrue(server.read("key3", i3, i4, 100).isEmpty()); assertOneValue(server.read("key3", i4, i5, 100), "value30"); assertOneValue(server.read("key3", i5, i6, 100), "value30"); @@ -131,7 +135,7 @@ public void testReadHistorizedForTwoValues() throws SQLException { }*/ @Test - public void testReadUpdatedKeys() throws SQLException { + public void testReadUpdatedKeys() { Assert.assertEquals("", StringUtils.join(server.readUpdatedKeys(i3, i4), ',')); Assert.assertEquals("key3,key4", StringUtils.join(server.readUpdatedKeys(i4, i5), ',')); Assert.assertEquals("key1,key2,key4", StringUtils.join(server.readUpdatedKeys(i5, i6), ',')); @@ -142,7 +146,7 @@ public void testReadUpdatedKeys() throws SQLException { } @Test - public void testReadLatest() throws SQLException { + public void testReadLatest() { StringBuilder sb = new StringBuilder(); server.readLatest().forEach(v -> sb.append(v.getKey()).append(':').append(v.getValue()).append(';')); Assert.assertEquals("key1:value10;key2:value20;key3:value31;key4:value42;", sb.toString()); @@ -152,7 +156,7 @@ public void testReadLatest() throws SQLException { // 10000->428s/60ms/58ms @Test @Ignore - public void testPerformance() throws SQLException { + public void testPerformance() { server.clearAllData(); long t0 = System.currentTimeMillis(); for (int i = 0; i < 10000; i++) { diff --git a/src/test/java/ch/mno/copper/store/db/DbValueStoreTest.java b/src/test/java/ch/mno/copper/store/db/DbValueStoreTest.java index dd3b763..4fd1899 100644 --- a/src/test/java/ch/mno/copper/store/db/DbValueStoreTest.java +++ b/src/test/java/ch/mno/copper/store/db/DbValueStoreTest.java @@ -1,23 +1,19 @@ package ch.mno.copper.store.db; -import org.junit.*; - import java.sql.SQLException; import java.time.Instant; -/** - * Created by dutoitc on 29.09.2017. - */ -@Ignore +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + public class DbValueStoreTest { - Instant i3 = Instant.parse("2015-10-21T07:27:48.00Z"); Instant i4 = Instant.parse("2015-10-21T07:27:49.00Z"); Instant i5 = Instant.parse("2015-10-21T07:28:00.00Z"); Instant i6 = Instant.parse("2015-10-21T07:28:01.00Z"); Instant i7 = Instant.parse("2015-10-21T07:28:02.00Z"); - Instant i8 = Instant.parse("2015-10-21T07:28:03.00Z"); - Instant i9 = Instant.parse("2045-10-21T07:28:00.00Z"); private DBValuesStore store; private DBServer server; @@ -25,7 +21,7 @@ public class DbValueStoreTest { @Before public void init() throws SQLException { DBServerManual.DBURL= "jdbc:h2:./copperdbtst"; - server = new DBServerManual(false, 12345); + server = new DBServerManual(false, 12346); store = new DBValuesStore(server); store.clearAllData(); store.put("key1", "value10", i5); diff --git a/src/test/java/ch/mno/copper/stories/LocalTest.java b/src/test/java/ch/mno/copper/stories/LocalTest.java index 0fc5e0a..4b2ee7e 100644 --- a/src/test/java/ch/mno/copper/stories/LocalTest.java +++ b/src/test/java/ch/mno/copper/stories/LocalTest.java @@ -1,8 +1,12 @@ package ch.mno.copper.stories; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.experimental.theories.DataPoints; @@ -10,13 +14,8 @@ import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; /** * Created by dutoitc on 10.02.2016. @@ -28,12 +27,12 @@ public class LocalTest { private static StoryGrammar grammar; @BeforeClass - public static void init() throws FileNotFoundException { + public static void init() { grammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } @Theory - public void checkStory(File file) throws IOException, ConnectorException { + public void checkStory(File file) throws IOException { System.out.println("Checking " + file.getName()); new Story(grammar, new FileInputStream(file), file.getName()); } @@ -41,7 +40,7 @@ public void checkStory(File file) throws IOException, ConnectorException { public static @DataPoints File[] candidates; static { try { - candidates = Files.walk(Paths.get("local/dsi")).filter(Files::isRegularFile).map(Path::toFile).toArray(s-> new File[s]); + candidates = Files.walk(Paths.get("local/dsi")).filter(Files::isRegularFile).map(Path::toFile).toArray(File[]::new); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/test/java/ch/mno/copper/stories/LocalTestDSI.java b/src/test/java/ch/mno/copper/stories/LocalTestDSI.java index 17c782e..02edf53 100644 --- a/src/test/java/ch/mno/copper/stories/LocalTestDSI.java +++ b/src/test/java/ch/mno/copper/stories/LocalTestDSI.java @@ -1,18 +1,18 @@ package ch.mno.copper.stories; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; + /** * Created by xsicdt on 11/02/16. */ @@ -27,34 +27,34 @@ public void init() throws FileNotFoundException { } @Test - public void testLocalJmx() throws IOException, ConnectorException { + public void testLocalJmx() throws IOException { Path path = Paths.get("dsi/RCFACEINCollectByJmx.txt"); new Story(grammar, new FileInputStream(path.toFile()), "RCFACEINCollectByJmx.txt"); } @Test - public void testLocalIn() throws IOException, ConnectorException { + public void testLocalIn() throws IOException { Path path = Paths.get("dsi/RCFACEINDbCollector.txt"); new Story(grammar, new FileInputStream(path.toFile()), "RCFACEINDbCollector.txt"); } @Test - public void testLocalVa() throws IOException, ConnectorException { + public void testLocalVa() throws IOException { Path path = Paths.get("dsi/RCFACEVADbCollector.txt"); new Story(grammar, new FileInputStream(path.toFile()), "RCFACEVADbCollector.txt"); } @Test - public void testLocalPP() throws IOException, ConnectorException { + public void testLocalPP() throws IOException { Path path = Paths.get("dsi/RCFACEPPDbCollector.txt"); new Story(grammar, new FileInputStream(path.toFile()), "RCFACEPPDbCollector.txt"); } @Test - public void testLocalPr() throws IOException, ConnectorException { + public void testLocalPr() throws IOException { Path path = Paths.get("dsi/RCFACEPRDbCollector.txt"); new Story(grammar, new FileInputStream(path.toFile()), "RCFACEPRDbCollector.txt"); } @@ -94,7 +94,7 @@ public void testLocalPr() throws IOException, ConnectorException { // } @Test - public void testLocalRep() throws IOException, ConnectorException { + public void testLocalRep() throws IOException { Path path = Paths.get("dsi/RCFACEDbReportByPushover.txt"); new Story(grammar, new FileInputStream(path.toFile()), "RCFACEDbReportByPushover.txt"); } diff --git a/src/test/java/ch/mno/copper/stories/StoryGrammarTest.java b/src/test/java/ch/mno/copper/stories/StoryGrammarTest.java index 26c552c..c2f8e32 100644 --- a/src/test/java/ch/mno/copper/stories/StoryGrammarTest.java +++ b/src/test/java/ch/mno/copper/stories/StoryGrammarTest.java @@ -1,17 +1,6 @@ package ch.mno.copper.stories; -import ch.mno.copper.collect.JdbcCollectorWrapper; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.helpers.SyntaxHelper; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; -import org.apache.commons.io.IOUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; @@ -20,6 +9,16 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import org.apache.commons.io.IOUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ch.mno.copper.collect.JdbcCollectorWrapper; +import ch.mno.copper.helpers.SyntaxHelper; +import ch.mno.copper.stories.data.Story; +import ch.mno.copper.stories.data.StoryGrammar; + /** * Created by dutoitc on 07.02.2016. */ @@ -28,7 +27,7 @@ public class StoryGrammarTest { private StoryGrammar storyGrammar; @Before - public void init() throws FileNotFoundException { + public void init() { storyGrammar = new StoryGrammar(Story.class.getResourceAsStream("/StoryGrammar.txt")); } @@ -257,7 +256,7 @@ public void testCSV2() { @Test - public void testJdbcStory() throws IOException, ConnectorException, URISyntaxException { + public void testJdbcStory() throws IOException, URISyntaxException { String pattern = storyGrammar.getPatternFull("MAIN"); // Pattern pattern1 = Pattern.compile(pattern, Pattern.DOTALL); URL resource = getClass().getResource("/OracleStory1.txt"); @@ -279,7 +278,7 @@ public void testJdbcStory() throws IOException, ConnectorException, URISyntaxExc @Test - public void testJdbcStory2() throws IOException, ConnectorException, URISyntaxException { + public void testJdbcStory2() throws IOException, URISyntaxException { String pattern = storyGrammar.getPatternFull("MAIN"); // Pattern pattern1 = Pattern.compile(pattern, Pattern.DOTALL); URL resource = getClass().getResource("/OracleStory2.txt"); diff --git a/src/test/java/ch/mno/copper/stories/data/StoryTest.java b/src/test/java/ch/mno/copper/stories/data/StoryTest.java index 0c281e0..21a60d3 100644 --- a/src/test/java/ch/mno/copper/stories/data/StoryTest.java +++ b/src/test/java/ch/mno/copper/stories/data/StoryTest.java @@ -1,15 +1,5 @@ package ch.mno.copper.stories.data; -import ch.mno.copper.collect.connectors.ConnectorException; -import ch.mno.copper.store.data.InstantValues; -import ch.mno.copper.store.StoreValue; -import ch.mno.copper.store.ValuesStore; -import ch.mno.copper.stories.data.Story; -import ch.mno.copper.stories.data.StoryGrammar; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; @@ -19,6 +9,15 @@ import java.util.List; import java.util.Map; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import ch.mno.copper.collect.connectors.ConnectorException; +import ch.mno.copper.store.StoreValue; +import ch.mno.copper.store.ValuesStore; +import ch.mno.copper.store.data.InstantValues; + /** * Created by xsicdt on 19/01/18. */ @@ -96,12 +95,12 @@ public List queryValues(Instant from, Instant to, long intervalSe } @Override - public void load() throws IOException { + public void load() { } @Override - public void save() throws IOException { + public void save() { }