diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorErrorHandler.java b/src/main/java/com/splunk/logging/HttpEventCollectorErrorHandler.java index b8e1074c..e8777989 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorErrorHandler.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorErrorHandler.java @@ -1,6 +1,6 @@ package com.splunk.logging; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorEventInfo.java b/src/main/java/com/splunk/logging/HttpEventCollectorEventInfo.java index 7fd9f977..0ab24a0f 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorEventInfo.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorEventInfo.java @@ -1,6 +1,6 @@ package com.splunk.logging; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorLog4jAppender.java b/src/main/java/com/splunk/logging/HttpEventCollectorLog4jAppender.java index 55f69fca..fc02d042 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorLog4jAppender.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorLog4jAppender.java @@ -40,7 +40,7 @@ @SuppressWarnings("serial") public final class HttpEventCollectorLog4jAppender extends AbstractAppender { - private HttpEventCollectorSender sender = null; + private HttpEventCollectorSender sender; private final boolean includeLoggerName; private final boolean includeThreadName; private final boolean includeMDC; @@ -154,10 +154,10 @@ public static HttpEventCollectorLog4jAppender createAppender( @PluginAttribute(value = "includeException", defaultBoolean = true) final boolean includeException, @PluginAttribute(value = "includeMarker", defaultBoolean = true) final boolean includeMarker, @PluginAttribute(value = "connect_timeout", defaultLong = HttpEventCollectorSender.TimeoutSettings.DEFAULT_CONNECT_TIMEOUT) final long connectTimeout, - @PluginAttribute(value = "call_timeout", defaultLong = HttpEventCollectorSender.TimeoutSettings.DEFAULT_CALL_TIMEOUT) final long callTimeout, - @PluginAttribute(value = "read_timeout", defaultLong = HttpEventCollectorSender.TimeoutSettings.DEFAULT_READ_TIMEOUT) final long readTimeout, - @PluginAttribute(value = "write_timeout", defaultLong = HttpEventCollectorSender.TimeoutSettings.DEFAULT_WRITE_TIMEOUT) final long writeTimeout, - @PluginAttribute(value = "termination_timeout", defaultLong = HttpEventCollectorSender.TimeoutSettings.DEFAULT_TERMINATION_TIMEOUT) final long terminationTimeout, + @PluginAttribute(value = "call_timeout") final long callTimeout, + @PluginAttribute(value = "read_timeout") final long readTimeout, + @PluginAttribute(value = "write_timeout") final long writeTimeout, + @PluginAttribute(value = "termination_timeout") final long terminationTimeout, @PluginElement("Layout") Layout layout, @PluginElement("Filter") final Filter filter ) diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorLoggingHandler.java b/src/main/java/com/splunk/logging/HttpEventCollectorLoggingHandler.java index 912d4bd2..9ce0861a 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorLoggingHandler.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorLoggingHandler.java @@ -1,6 +1,6 @@ package com.splunk.logging; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. @@ -93,7 +93,7 @@ * properties file. */ public final class HttpEventCollectorLoggingHandler extends Handler { - private HttpEventCollectorSender sender = null; + private HttpEventCollectorSender sender; private final String IncludeLoggerNameConfTag = "include_logger_name"; private final boolean includeLoggerName; private final String IncludeThreadNameConfTag = "include_thread_name"; diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorMiddleware.java b/src/main/java/com/splunk/logging/HttpEventCollectorMiddleware.java index e4123b7c..671501a3 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorMiddleware.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorMiddleware.java @@ -1,6 +1,6 @@ package com.splunk.logging; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. @@ -38,16 +38,16 @@ public class HttpEventCollectorMiddleware { * An interface that describes an abstract events sender working asynchronously. */ public interface IHttpSender { - public void postEvents(final List events, - IHttpSenderCallback callback); + void postEvents(final List events, + IHttpSenderCallback callback); } /** * Callback methods invoked by events sender. */ public interface IHttpSenderCallback { - public void completed(int statusCode, final String reply); - public void failed(final Exception ex); + void completed(int statusCode, final String reply); + void failed(final Exception ex); } /** diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorResendMiddleware.java b/src/main/java/com/splunk/logging/HttpEventCollectorResendMiddleware.java index b4e7b201..b1586790 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorResendMiddleware.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorResendMiddleware.java @@ -1,6 +1,6 @@ package com.splunk.logging; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. @@ -30,7 +30,7 @@ */ public class HttpEventCollectorResendMiddleware extends HttpEventCollectorMiddleware.HttpSenderMiddleware { - private long retriesOnError = 0; + private long retriesOnError; /** * Create a resend middleware component. diff --git a/src/main/java/com/splunk/logging/HttpEventCollectorSender.java b/src/main/java/com/splunk/logging/HttpEventCollectorSender.java index 01de77fa..50688889 100644 --- a/src/main/java/com/splunk/logging/HttpEventCollectorSender.java +++ b/src/main/java/com/splunk/logging/HttpEventCollectorSender.java @@ -1,6 +1,6 @@ package com.splunk.logging; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. @@ -27,7 +27,6 @@ import javax.net.ssl.*; import java.io.IOException; import java.io.Serializable; -import java.security.cert.CertificateException; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -63,7 +62,7 @@ public enum SendMode { Sequential, Parallel - }; + } /** * Recommended default values for events batching. @@ -79,7 +78,7 @@ public enum SendMode private long maxEventsBatchCount; private long maxEventsBatchSize; private Timer timer; - private List eventsBatch = new LinkedList(); + private List eventsBatch = new LinkedList<>(); private long eventsBatchSize = 0; // estimated total size of events batch private static final OkHttpClient httpSharedClient = new OkHttpClient(); // shared instance with the default settings private OkHttpClient httpClient = null; // shares the same connection pool and thread pools with the shared instance @@ -354,11 +353,11 @@ private void startHttpClient() { final TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override - public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override - public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) { } @Override @@ -377,12 +376,7 @@ public java.security.cert.X509Certificate[] getAcceptedIssuers() { builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]); } catch (Exception ignored) { /* nop */ } - builder.hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } - }); + builder.hostnameVerifier((hostname, session) -> true); } httpClient = builder.build(); diff --git a/src/main/java/com/splunk/logging/SplunkCimLogEvent.java b/src/main/java/com/splunk/logging/SplunkCimLogEvent.java index 861c374b..9738e80f 100644 --- a/src/main/java/com/splunk/logging/SplunkCimLogEvent.java +++ b/src/main/java/com/splunk/logging/SplunkCimLogEvent.java @@ -61,7 +61,7 @@ public class SplunkCimLogEvent { * @param eventID event ID */ public SplunkCimLogEvent(String eventName, String eventID) { - entries = new LinkedHashMap(); + entries = new LinkedHashMap<>(); addField(PREFIX_NAME, eventName); addField(PREFIX_EVENT_ID, eventID); @@ -157,7 +157,7 @@ public String toString() { private static final String THROWABLE_MESSAGE = "throwable_message"; private static final String THROWABLE_STACKTRACE_ELEMENTS = "stacktrace_elements"; - /** + /* * Splunk Common Information Model(CIM) Fields */ diff --git a/src/main/java/com/splunk/logging/TcpAppender.java b/src/main/java/com/splunk/logging/TcpAppender.java index eeb00511..d9d3fbe6 100644 --- a/src/main/java/com/splunk/logging/TcpAppender.java +++ b/src/main/java/com/splunk/logging/TcpAppender.java @@ -148,13 +148,7 @@ private SocketConnector initSocketConnector() { connector = getDefaultSocketConnectorConstr().newInstance(address, port, 0, reconnectionDelay); } - catch (InvocationTargetException e) { - throwRuntimeException(e); - } - catch (InstantiationException e) { - throwRuntimeException(e); - } - catch (IllegalAccessException e) { + catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { throwRuntimeException(e); } @@ -243,14 +237,11 @@ public void start() { // Dispatch this instance of the appender. if (!errorPresent) { - queue = queueSize <= 0 ? new SynchronousQueue() : new ArrayBlockingQueue(queueSize); - ThreadFactory factory = new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r, "splunk-tcp-appender"); - t.setDaemon(true); - return t; - } + queue = queueSize <= 0 ? new SynchronousQueue<>() : new ArrayBlockingQueue<>(queueSize); + ThreadFactory factory = r -> { + Thread t = new Thread(r, "splunk-tcp-appender"); + t.setDaemon(true); + return t; }; executor = Executors.newSingleThreadExecutor(factory); executor.execute(this); diff --git a/src/main/java/com/splunk/logging/serialization/EventInfoTypeAdapter.java b/src/main/java/com/splunk/logging/serialization/EventInfoTypeAdapter.java index 49f1bf3d..4417a922 100644 --- a/src/main/java/com/splunk/logging/serialization/EventInfoTypeAdapter.java +++ b/src/main/java/com/splunk/logging/serialization/EventInfoTypeAdapter.java @@ -6,7 +6,6 @@ package com.splunk.logging.serialization; import com.google.gson.*; -import com.splunk.logging.EventBodySerializer; import com.splunk.logging.HttpEventCollectorEventInfo; import java.lang.reflect.Type; diff --git a/src/main/java/com/splunk/logging/serialization/HecJsonSerializer.java b/src/main/java/com/splunk/logging/serialization/HecJsonSerializer.java index 1872c8b0..ff54bc29 100644 --- a/src/main/java/com/splunk/logging/serialization/HecJsonSerializer.java +++ b/src/main/java/com/splunk/logging/serialization/HecJsonSerializer.java @@ -13,7 +13,6 @@ import com.splunk.logging.hec.MetadataTags; import java.util.*; -import java.util.stream.Collectors; public class HecJsonSerializer { private static final Set KEYWORDS = MetadataTags.HEC_TAGS; diff --git a/src/test/java/HttpEventCollectorUnitTest.java b/src/test/java/HttpEventCollectorUnitTest.java index 2961934b..dd482588 100644 --- a/src/test/java/HttpEventCollectorUnitTest.java +++ b/src/test/java/HttpEventCollectorUnitTest.java @@ -1,4 +1,4 @@ -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. @@ -17,26 +17,21 @@ */ import java.io.IOException; -import java.io.OutputStream; -import java.net.InetSocketAddress; import com.splunk.logging.HttpEventCollectorErrorHandler; import com.splunk.logging.HttpEventCollectorEventInfo; import org.junit.Assert; import org.junit.Test; -import sun.rmi.runtime.Log; import java.io.ByteArrayInputStream; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.logging.LogManager; -import java.util.logging.Logger; public class HttpEventCollectorUnitTest { @Test public void log4j_simple() throws Exception { - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); String loggerName = "splunk.log4jSimple"; userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", "11111111-2222-3333-4444-555555555555"); @@ -53,9 +48,9 @@ public void log4j_simple() throws Exception { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == 1); - Assert.assertTrue(events.get(0).getMessage().compareTo("hello log4j") == 0); - Assert.assertTrue(events.get(0).getSeverity().compareTo("INFO") == 0); + Assert.assertEquals(1, events.size()); + Assert.assertEquals(0, events.get(0).getMessage().compareTo("hello log4j")); + Assert.assertEquals(0, events.get(0).getSeverity().compareTo("INFO")); } }; LOG4J.info("hello log4j"); @@ -63,12 +58,12 @@ public void input(List events) { LOG4J.info("hello log4j"); if (HttpEventCollectorUnitTestMiddleware.eventsReceived == 0) sleep(15000); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 3); + Assert.assertEquals(3, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test public void logback_simple() throws Exception { - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); final String loggerName = "splunk.logback"; userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", "11111111-2222-3333-4444-555555555555"); @@ -83,16 +78,16 @@ public void logback_simple() throws Exception { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == 1); - Assert.assertTrue(events.get(0).getMessage().compareTo("hello logback") == 0); - Assert.assertTrue(events.get(0).getSeverity().compareTo("ERROR") == 0); - Assert.assertTrue(events.get(0).getLoggerName().compareTo(loggerName) == 0); + Assert.assertEquals(1, events.size()); + Assert.assertEquals(0, events.get(0).getMessage().compareTo("hello logback")); + Assert.assertEquals(0, events.get(0).getSeverity().compareTo("ERROR")); + Assert.assertEquals(0, events.get(0).getLoggerName().compareTo(loggerName)); } }; LOGBACK.error("hello logback"); LOGBACK.error("hello logback"); LOGBACK.error("hello logback"); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 3); + Assert.assertEquals(3, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -115,15 +110,15 @@ public void java_util_logger_simple() { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == 1); - Assert.assertTrue(events.get(0).getMessage().compareTo("hello java logger") == 0); - Assert.assertTrue(events.get(0).getSeverity().compareTo("WARNING") == 0); + Assert.assertEquals(1, events.size()); + Assert.assertEquals(0, events.get(0).getMessage().compareTo("hello java logger")); + Assert.assertEquals(0, events.get(0).getSeverity().compareTo("WARNING")); } }; LOGGER.warning("hello java logger"); LOGGER.warning("hello java logger"); LOGGER.warning("hello java logger"); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 3); + Assert.assertEquals(3, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -149,16 +144,14 @@ public HttpEventCollectorUnitTestMiddleware.HttpResponse output() { ); } }; - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - HttpEventCollectorErrorHandler.ServerErrorException serverErrorException = - (HttpEventCollectorErrorHandler.ServerErrorException) ex; - Assert.assertTrue(serverErrorException.getReply().compareTo("{\"text\":\"error\",\"code\":4}") == 0); - Assert.assertTrue(serverErrorException.getErrorCode() == 4); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + HttpEventCollectorErrorHandler.ServerErrorException serverErrorException = + (HttpEventCollectorErrorHandler.ServerErrorException) ex; + Assert.assertEquals(0, serverErrorException.getReply().compareTo("{\"text\":\"error\",\"code\":4}")); + Assert.assertEquals(4, serverErrorException.getErrorCode()); }); LOGGER.info("hello"); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 1); + Assert.assertEquals(1, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -180,8 +173,8 @@ public void java_util_logger_resend() { int retries = 0; @Override public void input(List events) { - Assert.assertTrue(events.get(0).getMessage().compareTo("hello") == 0); - Assert.assertTrue(events.get(0).getSeverity().compareTo("INFO") == 0); + Assert.assertEquals(0, events.get(0).getMessage().compareTo("hello")); + Assert.assertEquals(0, events.get(0).getSeverity().compareTo("INFO")); } @Override public HttpEventCollectorUnitTestMiddleware.HttpResponse output() { @@ -198,7 +191,7 @@ public HttpEventCollectorUnitTestMiddleware.HttpResponse output() { }; LOGGER.info("hello"); // the system should make 2 retries - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 2); + Assert.assertEquals(2, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -219,8 +212,8 @@ public void java_util_logger_resend_max_retries() { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.get(0).getMessage().compareTo("hello") == 0); - Assert.assertTrue(events.get(0).getSeverity().compareTo("INFO") == 0); + Assert.assertEquals(0, events.get(0).getMessage().compareTo("hello")); + Assert.assertEquals(0, events.get(0).getSeverity().compareTo("INFO")); } @Override public HttpEventCollectorUnitTestMiddleware.HttpResponse output() { @@ -229,14 +222,12 @@ public HttpEventCollectorUnitTestMiddleware.HttpResponse output() { 0, "{\"text\":\"error\",\"code\":4}"); } }; - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - // ignore errors - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + // ignore errors }); LOGGER.info("hello"); // the system should make only 2 retries and stop after that - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 3); + Assert.assertEquals(3, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -254,16 +245,16 @@ public void java_util_logger_batching() { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == 3); - Assert.assertTrue(events.get(0).getMessage().compareTo("one") == 0); - Assert.assertTrue(events.get(1).getMessage().compareTo("two") == 0); - Assert.assertTrue(events.get(2).getMessage().compareTo("three") == 0); + Assert.assertEquals(3, events.size()); + Assert.assertEquals(0, events.get(0).getMessage().compareTo("one")); + Assert.assertEquals(0, events.get(1).getMessage().compareTo("two")); + Assert.assertEquals(0, events.get(2).getMessage().compareTo("three")); } }; LOGGER.info("one"); LOGGER.info("two"); LOGGER.info("three"); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 3); + Assert.assertEquals(3, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -280,13 +271,13 @@ public void java_util_logger_batching_default_count() { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == DefaultBatchCount); + Assert.assertEquals(DefaultBatchCount, events.size()); } }; for (int i = 0; i < DefaultBatchCount * 100; i ++) { LOGGER.info("*"); } - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == DefaultBatchCount * 100); + Assert.assertEquals(DefaultBatchCount * 100, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -303,13 +294,13 @@ public void java_util_logger_batching_default_size() { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == 1); + Assert.assertEquals(1, events.size()); } }; for (int i = 0; i < 10; i ++) { LOGGER.info(repeat("x", DefaultBatchSize)); } - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 10); + Assert.assertEquals(10, HttpEventCollectorUnitTestMiddleware.eventsReceived); } @Test @@ -326,14 +317,14 @@ public void java_util_logger_batching_default_interval() { HttpEventCollectorUnitTestMiddleware.io = new HttpEventCollectorUnitTestMiddleware.IO() { @Override public void input(List events) { - Assert.assertTrue(events.size() == 1); + Assert.assertEquals(1, events.size()); } }; LOGGER.info("=|:-)"); sleep(DefaultInterval / 2); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 0); + Assert.assertEquals(0, HttpEventCollectorUnitTestMiddleware.eventsReceived); sleep(DefaultInterval); - Assert.assertTrue(HttpEventCollectorUnitTestMiddleware.eventsReceived == 1); + Assert.assertEquals(1, HttpEventCollectorUnitTestMiddleware.eventsReceived); } //-------------------------------------------------------------------------- @@ -347,7 +338,7 @@ private void readConf(final String conf) { } } - private final String repeat(String str, int times) { + private String repeat(String str, int times) { StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < times ; i ++) sb.append(str); diff --git a/src/test/java/HttpEventCollectorUnitTestMiddleware.java b/src/test/java/HttpEventCollectorUnitTestMiddleware.java index 0d272cd0..57410f8c 100644 --- a/src/test/java/HttpEventCollectorUnitTestMiddleware.java +++ b/src/test/java/HttpEventCollectorUnitTestMiddleware.java @@ -3,7 +3,7 @@ import java.util.List; -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. diff --git a/src/test/java/HttpEventCollector_JavaLoggingTest.java b/src/test/java/HttpEventCollector_JavaLoggingTest.java index 32127d78..588ce87d 100644 --- a/src/test/java/HttpEventCollector_JavaLoggingTest.java +++ b/src/test/java/HttpEventCollector_JavaLoggingTest.java @@ -29,9 +29,10 @@ public final class HttpEventCollector_JavaLoggingTest { - private String httpEventCollectorName = "JavaLoggingTest"; - List> errors = new ArrayList>(); - List logEx = new ArrayList(); + private static final String httpEventCollectorName = "JavaLoggingTest"; + + private final List> errors = new ArrayList<>(); + private final List logEx = new ArrayList<>(); /** * sending a message via httplogging using java.logging to splunk @@ -43,13 +44,13 @@ public void canSendEventUsingJavaLogging() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLoggerNoOptions"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging canSendEventUsingJavaLogging}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging canSendEventUsingJavaLogging}", date); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -67,7 +68,7 @@ public void canSendEventUsingJavaLoggingWithOptions() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLoggerWithOptions"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); userInputs.put("user_host", "host.example.com"); @@ -77,7 +78,7 @@ public void canSendEventUsingJavaLoggingWithOptions() throws Exception { TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging canSendEventUsingJavaLoggingWithOptions}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging canSendEventUsingJavaLoggingWithOptions}", date); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -95,7 +96,7 @@ public void sendBatchedEventsUsingJavaLogging() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkBatchLogger"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_batch_interval", "0"); userInputs.put("user_batch_size_bytes", "0"); @@ -104,7 +105,7 @@ public void sendBatchedEventsUsingJavaLogging() throws Exception { TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging sendBatchedEventsUsingJavaLogging}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging sendBatchedEventsUsingJavaLogging}", date); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -123,11 +124,11 @@ public void sendBatchedEventsByCount() throws Exception { //clean out the events cache by setting send events immediately String loggerName = "splunkLoggerCountCleanCache"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging sendBatchedEventsByCount}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging sendBatchedEventsByCount}", new Date()); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -144,24 +145,24 @@ public void sendBatchedEventsByCount() throws Exception { TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); logger = Logger.getLogger(loggerName); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging1}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging1}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 1"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging2}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging2}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 2"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging3}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging3}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 3"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging4}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging4}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 4"); @@ -170,7 +171,7 @@ public void sendBatchedEventsByCount() throws Exception { Thread.sleep(6000); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging5}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging5}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); @@ -188,7 +189,7 @@ public void sendBatchedEventsByBatchsize() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkBatchLoggerSize"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_batch_interval", "0"); userInputs.put("user_batch_size_bytes", "500"); @@ -200,14 +201,14 @@ public void sendBatchedEventsByBatchsize() throws Exception { TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); Logger logger = Logger.getLogger(loggerName); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); int size = 0; - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 1}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 1}", new Date()); size += jsonMsg.length(); logger.info(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 2}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 2}", new Date()); size += jsonMsg.length(); logger.info(jsonMsg); msgs.add(jsonMsg); @@ -215,7 +216,7 @@ public void sendBatchedEventsByBatchsize() throws Exception { Thread.sleep(6000); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 3, adding more msg to exceed the maxsize}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 3, adding more msg to exceed the maxsize}", new Date()); while (size + jsonMsg.length() < 550) { jsonMsg = String.format("%saaaaa", jsonMsg); } @@ -236,19 +237,17 @@ public void errorHandlingInvalidToken() throws Exception { errors.clear(); logEx.clear(); //define error callback - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - synchronized (errors) { - errors.add(data); - logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + synchronized (errors) { + errors.add(data); + logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); } }); //create a token used for httpEventCollector logging, then make it becomes invalid String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "errorHandlingInvalidToken"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); @@ -257,14 +256,14 @@ public void error(final List data, final Exception //disable the token so that it becomes invalid TestUtil.disableHttpEventCollector(httpEventCollectorName); Thread.sleep(5000); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event disabled token }", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event disabled token }", new Date()); logger.info(jsonMsg); Thread.sleep(2000); //delete the token so that it becomes invalid TestUtil.deleteHttpEventCollectorToken(httpEventCollectorName); Thread.sleep(5000); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event deleted token}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event deleted token}", new Date()); logger.info(jsonMsg); //wait for async process to return the error @@ -275,12 +274,9 @@ public void error(final List data, final Exception Thread.sleep(1000); } - if (logEx == null) - Assert.fail("didn't catch errors"); - System.out.println("======print logEx"); - System.out.println(logEx.toString()); + System.out.println(logEx); System.out.println("======finish print logEx"); Assert.assertEquals("Invalid token", logEx.get(1).getErrorText()); Assert.assertEquals(4, logEx.get(1).getErrorCode()); @@ -304,19 +300,17 @@ public void errorHandlingDisabledHttpEventCollectorEndpoint() throws Exception { logEx.clear(); //define error callback - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - synchronized (errors) { - errors.add(data); - logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + synchronized (errors) { + errors.add(data); + logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); } }); //create a token used for httpEventCollector logging, then make it becomes invalid String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "disabledendpoint"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); @@ -324,7 +318,7 @@ public void error(final List data, final Exception //disable httpEventCollector endpoint TestUtil.disableHttpEventCollector(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event httpEventCollector disabled}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event httpEventCollector disabled}", new Date()); logger.info(jsonMsg); //wait for async process to return the error @@ -338,13 +332,11 @@ public void error(final List data, final Exception // Enable httpEventCollector endpoint TestUtil.enableHttpEventCollector(); - if (logEx == null) - Assert.fail("didn't catch errors"); Assert.assertEquals(1, errors.size()); - System.out.println(logEx.toString()); + System.out.println(logEx); if (!StringUtils.containsAny(logEx.toString(), "Failed to connect to", "Remote host terminated the handshake", "Connection reset")) - Assert.fail(String.format("Unexpected error message '%s'", logEx.toString())); + Assert.fail(String.format("Unexpected error message '%s'", logEx)); } @@ -364,11 +356,11 @@ private String queueEvents() throws Exception { //clean out the events cache by setting send events immediately String loggerName = "splunkLoggerqueueEventsCleanCache"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging}", new Date()); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -385,9 +377,9 @@ private String queueEvents() throws Exception { TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); logger = Logger.getLogger(loggerName); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging1}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging1}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); TestUtil.verifyNoEventSentToSplunk(msgs); @@ -407,7 +399,7 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLoggerMultipleEvents"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); userInputs.put("user_index", indexName); @@ -417,7 +409,7 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { Logger logger = Logger.getLogger(loggerName); //send multiple events and verify they are indexed in the order of sending - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); Date date = new Date(); int totalEventsCount = 1000; String prefix = "javalogging multiple events"; @@ -459,7 +451,7 @@ public void canSendEventUsingJavaLoggingWithUserEventBodySerializer() throws Exc String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLoggerBodySerializer"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); userInputs.put("user_eventBodySerializer", "TestEventBodySerializer"); @@ -467,7 +459,7 @@ public void canSendEventUsingJavaLoggingWithUserEventBodySerializer() throws Exc TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); Date date = new Date(); - String jsonMsg = String.format("EventDate:%s, EventMsg:test event for java logging With User EventBodySerializer", date.toString()); + String jsonMsg = String.format("EventDate:%s, EventMsg:test event for java logging With User EventBodySerializer", date); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -487,7 +479,7 @@ public void canSendEventUsingJavaLoggingWithUserEventHeaderSerializer() throws E String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLoggerHeaderSerializer"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_logger_name", loggerName); userInputs.put("user_eventHeaderSerializer", "TestEventHeaderSerializer"); @@ -495,7 +487,7 @@ public void canSendEventUsingJavaLoggingWithUserEventHeaderSerializer() throws E TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); Date date = new Date(); - String jsonMsg = String.format("EventDate:%s, EventMsg:test event for java logging With User EventHeaderSerializer", date.toString()); + String jsonMsg = String.format("EventDate:%s, EventMsg:test event for java logging With User EventHeaderSerializer", date); Logger logger = Logger.getLogger(loggerName); logger.info(jsonMsg); @@ -515,7 +507,7 @@ private void canSendJsonEventUsingUtilLoggerWithSourceType(final String sourceTy TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); - final List msgs = new ArrayList(); + final List msgs = new ArrayList<>(); final long timeMillsec = new Date().getTime(); diff --git a/src/test/java/HttpEventCollector_Log4j2Test.java b/src/test/java/HttpEventCollector_Log4j2Test.java index b049f812..20c9878a 100644 --- a/src/test/java/HttpEventCollector_Log4j2Test.java +++ b/src/test/java/HttpEventCollector_Log4j2Test.java @@ -14,7 +14,6 @@ * under the License. */ -import java.io.*; import java.util.*; import com.google.gson.JsonObject; @@ -30,32 +29,32 @@ public final class HttpEventCollector_Log4j2Test { private String httpEventCollectorName = "Log4j2Test"; - List> errors = new ArrayList>(); - List logEx = new ArrayList<>(); + private final List> errors = new ArrayList<>(); + private final List logEx = new ArrayList<>(); /** * sending a message via httplogging using log4j2 to splunk */ @Test - public void canSendEventUsingLog4j2() throws Exception, IOException, InterruptedException { + public void canSendEventUsingLog4j2() throws Exception { TestUtil.enableHttpEventCollector(); String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLogger4j2"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); org.apache.logging.log4j.core.LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); //use httplogger - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for log4j2}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for log4j2}", date); Logger logger = context.getLogger(loggerName); logger.info(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for log4j2}", date.toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for log4j2}", date); logger.error(jsonMsg); msgs.add(jsonMsg); @@ -70,11 +69,11 @@ public void canSendEventUsingLog4j2() throws Exception, IOException, Interrupted * sending a message via httplogging using log4j2 to splunk and set index, source and sourcetype */ @Test - public void canSendEventUsingLog4j2WithOptions() throws Exception, IOException, InterruptedException { + public void canSendEventUsingLog4j2WithOptions() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLogger4j2WithOptions"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_index", "main"); @@ -84,16 +83,16 @@ public void canSendEventUsingLog4j2WithOptions() throws Exception, IOException, org.apache.logging.log4j.core.LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); //use httplogger - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for log4j2}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for log4j2}", date); Logger logger = context.getLogger(loggerName); logger.info(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for log4j2}", date.toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for log4j2}", date); logger.error(jsonMsg); msgs.add(jsonMsg); @@ -112,21 +111,20 @@ public void sendBatchedEventsByCount() throws Exception { //clean out the events cache by setting send events immediately String loggerName = "splunkLoggerCountCleanCache"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging}", new Date()); Logger logger = context.getLogger(loggerName); logger.info(jsonMsg); loggerName = "splunkBatchLoggerCount"; - userInputs = new HashMap(); + userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_batch_interval","0"); userInputs.put("user_batch_size_count", "5"); - userInputs.put("user_logger_name", loggerName); userInputs.put("user_host", "host.example.com"); userInputs.put("user_source", "splunktest_BatchCount"); userInputs.put("user_sourcetype", "battlecat_BatchCount"); @@ -134,24 +132,24 @@ public void sendBatchedEventsByCount() throws Exception { context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); logger = context.getLogger(loggerName); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging1}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging1}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 1"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging2}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging2}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 2"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging3}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging3}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 3"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging4}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging4}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 4"); @@ -160,7 +158,7 @@ public void sendBatchedEventsByCount() throws Exception { Thread.sleep(6000); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging5}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for java logging5}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); @@ -173,10 +171,10 @@ public void sendBatchedEventsByCount() throws Exception { * sending a message via httplogging using java.logging with batched_size_bytes */ @Test - public void sendBatchedEventsByBatchsize() throws Exception { + public void sendBatchedEventsByBatchSize() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLoggerBatchSize"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_batch_size_bytes", "500"); @@ -188,13 +186,13 @@ public void sendBatchedEventsByBatchsize() throws Exception { LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); Logger logger = context.getLogger(loggerName); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); int size = 0; - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for log4j size 1}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for log4j size 1}", new Date()); logger.info(jsonMsg); size += jsonMsg.length(); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for log4j size 2}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for log4j size 2}", new Date()); size += jsonMsg.length(); logger.info(jsonMsg); msgs.add(jsonMsg); @@ -202,7 +200,7 @@ public void sendBatchedEventsByBatchsize() throws Exception { Thread.sleep(6000); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for log4j size 3, adding more msg to exceed the maxsize}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for log4j size 3, adding more msg to exceed the maxsize}", new Date()); while (size + jsonMsg.length() < 550) { jsonMsg = String.format("%saaaaa", jsonMsg); } @@ -222,12 +220,10 @@ public void errorHandlingInvalidToken() throws Exception { errors.clear(); logEx.clear(); //define error callback - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - synchronized (errors) { - errors.add(data); - logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + synchronized (errors) { + errors.add(data); + logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); } }); @@ -235,7 +231,7 @@ public void error(final List data, final Exception httpEventCollectorName = "wrongtoken"; String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "errorHandlingInvalidTokenLog4j"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); @@ -244,14 +240,14 @@ public void error(final List data, final Exception //disable the token so that it becomes invalid TestUtil.disableHttpEventCollector(httpEventCollectorName); Thread.sleep(5000); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event disabled token }", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event disabled token }", new Date()); logger.info(jsonMsg); Thread.sleep(5000); //delete the token so that it becomes invalid TestUtil.deleteHttpEventCollectorToken(httpEventCollectorName); Thread.sleep(5000); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event deleted token}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event deleted token}", new Date()); logger.info(jsonMsg); //wait for async process to return the error @@ -262,9 +258,6 @@ public void error(final List data, final Exception Thread.sleep(1000); } - if (logEx == null) - Assert.fail("didn't catch errors"); - for (List infos : errors) { for (HttpEventCollectorEventInfo info : infos) { System.out.println(info.getMessage()); @@ -272,7 +265,7 @@ public void error(final List data, final Exception } System.out.println("======print logEx"); - System.out.println(logEx.toString()); + System.out.println(logEx); System.out.println("======finish print logEx"); Assert.assertEquals("Invalid token", logEx.get(1).getErrorText()); Assert.assertEquals(4, logEx.get(1).getErrorCode()); @@ -291,12 +284,10 @@ public void errorHandlingDisabledHttpEventCollectorEndpoint() throws Exception { logEx.clear(); //define error callback - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - synchronized (errors) { - errors.add(data); - logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + synchronized (errors) { + errors.add(data); + logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); } }); @@ -304,7 +295,7 @@ public void error(final List data, final Exception httpEventCollectorName = "wrongtoken"; String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "errorHandlingDisabledHttpEventCollectorEndpoint"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); @@ -314,7 +305,7 @@ public void error(final List data, final Exception //disable httpEventCollector endpoint TestUtil.disableHttpEventCollector(); Thread.sleep(1000); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event httpEventCollector disabled}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event httpEventCollector disabled}", new Date()); logger.info(jsonMsg); //wait for async process to return the error @@ -325,13 +316,11 @@ public void error(final List data, final Exception Thread.sleep(1000); } - if (logEx == null) - Assert.fail("didn't catch errors"); Assert.assertTrue(errors.size() >= 1); - System.out.println(logEx.toString()); + System.out.println(logEx); if (!StringUtils.containsAny(logEx.toString(), "Failed to connect to", "Remote host terminated the handshake", "Connection reset")) - Assert.fail(String.format("Unexpected error message '%s'", logEx.toString())); + Assert.fail(String.format("Unexpected error message '%s'", logEx)); } /** @@ -345,7 +334,7 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { TestUtil.createIndex(indexName); String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkLogger4j2OrderOfSent"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_index", indexName); @@ -354,7 +343,6 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { org.apache.logging.log4j.core.LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); //send multiple events and verify they are indexed in the order of sending - List msgs = new ArrayList(); Date date = new Date(); int totalEventsCount = 1000; Logger logger = context.getLogger(loggerName); @@ -362,7 +350,6 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { for (int i = 0; i < totalEventsCount; i++) { String jsonMsg = String.format("%s %s", prefix,i); logger.info(jsonMsg); - msgs.add(jsonMsg); } TestUtil.verifyEventsSentInOrder(prefix,totalEventsCount,indexName); @@ -400,7 +387,7 @@ private void canSendJsonEventUsingUtilLoggerWithSourceType(final String sourceTy final Logger logger = context.getLogger(loggerName); - final List msgs = new ArrayList(); + final List msgs = new ArrayList<>(); final long timeMillsec = new Date().getTime(); diff --git a/src/test/java/HttpEventCollector_LogbackTest.java b/src/test/java/HttpEventCollector_LogbackTest.java index 3fa2c20e..b28b5575 100644 --- a/src/test/java/HttpEventCollector_LogbackTest.java +++ b/src/test/java/HttpEventCollector_LogbackTest.java @@ -30,8 +30,8 @@ public final class HttpEventCollector_LogbackTest { private String httpEventCollectorName = "LogbackTest"; - List> errors = new ArrayList>(); - List logEx = new ArrayList(); + private final List> errors = new ArrayList<>(); + private final List logEx = new ArrayList<>(); /** * sending a message via httplogging using logback to splunk @@ -42,25 +42,25 @@ public void canSendEventUsingLogback() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "logBackLogger"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_defined_httpEventCollector_token", token); TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for Logback Test}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for Logback Test}", date); Logger logger = LoggerFactory.getLogger(loggerName); logger.info(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for Logback Test}", date.toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for Logback Test}", date); logger.error(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test debug for Logback Test}", date.toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test debug for Logback Test}", date); logger.debug(jsonMsg); msgs.add(jsonMsg); @@ -76,7 +76,7 @@ public void canSendEventUsingLogbackWithOptions() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "logBackLogger"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_host", "host.example.com"); @@ -84,19 +84,19 @@ public void canSendEventUsingLogbackWithOptions() throws Exception { userInputs.put("user_sourcetype", "battlecat"); TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); Date date = new Date(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for Logback Test}", date.toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for Logback Test}", date); Logger logger = LoggerFactory.getLogger(loggerName); logger.info(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for Logback Test}", date.toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test error for Logback Test}", date); logger.error(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test debug for Logback Test}", date.toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test debug for Logback Test}", date); logger.debug(jsonMsg); msgs.add(jsonMsg); @@ -112,7 +112,7 @@ public void canSendBatchEventByCount() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "logBackBatchLoggerCount"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); //userInputs.put("user_batch_interval","0"); userInputs.put("user_batch_size_count", "5"); @@ -125,23 +125,23 @@ public void canSendBatchEventByCount() throws Exception { TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); Logger logger = LoggerFactory.getLogger(loggerName); - List msgs = new ArrayList(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 1}", new Date().toString()); + List msgs = new ArrayList<>(); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 1}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 1"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 2}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 2}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 2"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 3}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 3}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 3"); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 4}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 4}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); System.out.println("event 4"); @@ -150,7 +150,7 @@ public void canSendBatchEventByCount() throws Exception { Thread.sleep(6000); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 5}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'this is a test event for logback 5}", new Date()); logger.info(jsonMsg); msgs.add(jsonMsg); @@ -168,7 +168,7 @@ public void canSendBatchEventBySize() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "logBackBatchLoggerSize"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_batch_size_bytes", "500"); userInputs.put("user_logger_name", loggerName); @@ -179,14 +179,14 @@ public void canSendBatchEventBySize() throws Exception { TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); Logger logger = LoggerFactory.getLogger(loggerName); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); int size = 0; - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 1}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 1}", new Date()); size += jsonMsg.length(); logger.info(jsonMsg); msgs.add(jsonMsg); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 2}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 2}", new Date()); size += jsonMsg.length(); logger.info(jsonMsg); msgs.add(jsonMsg); @@ -194,7 +194,7 @@ public void canSendBatchEventBySize() throws Exception { Thread.sleep(6000); TestUtil.verifyNoEventSentToSplunk(msgs); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 3, adding more msg to exceed the maxsize}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event for java logging size 3, adding more msg to exceed the maxsize}", new Date()); while (size + jsonMsg.length() < 550) { jsonMsg = String.format("%saaaaa", jsonMsg); } @@ -216,12 +216,10 @@ public void errorHandlingInvalidToken() throws Exception { errors.clear(); logEx.clear(); //define error callback - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - synchronized (errors) { - errors.add(data); - logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + synchronized (errors) { + errors.add(data); + logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); } }); @@ -229,7 +227,7 @@ public void error(final List data, final Exception httpEventCollectorName = "wrongtoken"; String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "wrongToken"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); @@ -237,12 +235,12 @@ public void error(final List data, final Exception //disable the token so that it becomes invalid TestUtil.disableHttpEventCollector(httpEventCollectorName); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event disabled token }", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event disabled token }", new Date()); logger.info(jsonMsg); //delete the token so that it becomes invalid TestUtil.deleteHttpEventCollectorToken(httpEventCollectorName); - jsonMsg = String.format("{EventDate:%s, EventMsg:'test event deleted token}", new Date().toString()); + jsonMsg = String.format("{EventDate:%s, EventMsg:'test event deleted token}", new Date()); logger.info(jsonMsg); //wait for async process to return the error @@ -253,12 +251,8 @@ public void error(final List data, final Exception Thread.sleep(1000); } - if (logEx == null) - Assert.fail("didn't catch errors"); - - System.out.println("======print logEx"); - System.out.println(logEx.toString()); + System.out.println(logEx); System.out.println("======finish print logEx"); Assert.assertEquals("Invalid token", logEx.get(1).getErrorText()); Assert.assertEquals(4, logEx.get(1).getErrorCode()); @@ -282,12 +276,10 @@ public void errorHandlingDisabledHttpEventCollectorEndpoint() throws Exception { logEx.clear(); //define error callback - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - synchronized (errors) { - errors.add(data); - logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + synchronized (errors) { + errors.add(data); + logEx.add((HttpEventCollectorErrorHandler.ServerErrorException) ex); } }); @@ -295,7 +287,7 @@ public void error(final List data, final Exception httpEventCollectorName = "wrongtoken"; String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "wrongToken"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); @@ -304,7 +296,7 @@ public void error(final List data, final Exception //disable httpEventCollector endpoint TestUtil.disableHttpEventCollector(); - String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event httpEventCollector disabled}", new Date().toString()); + String jsonMsg = String.format("{EventDate:%s, EventMsg:'test event httpEventCollector disabled}", new Date()); logger.info(jsonMsg); //wait for async process to return the error @@ -316,14 +308,12 @@ public void error(final List data, final Exception } TestUtil.enableHttpEventCollector(); - - if (logEx == null) - Assert.fail("didn't catch errors"); + Assert.assertEquals(1, errors.size()); - System.out.println(logEx.toString()); + System.out.println(logEx); if (!StringUtils.containsAny(logEx.toString(), "Failed to connect to", "Remote host terminated the handshake", "Connection reset")) - Assert.fail(String.format("Unexpected error message '%s'", logEx.toString())); + Assert.fail(String.format("Unexpected error message '%s'", logEx)); } /** @@ -337,7 +327,7 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { TestUtil.createIndex(indexName); String loggerName = "logBackLogger"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_defined_httpinput_token", token); @@ -346,7 +336,7 @@ public void eventsIsIndexedInOrderOfSent() throws Exception { TestUtil.resetLogbackConfiguration("logback_template.xml", "logback.xml", userInputs); Date date = new Date(); - List msgs = new ArrayList(); + List msgs = new ArrayList<>(); Logger logger = LoggerFactory.getLogger(loggerName); //send multiple events and verify they are indexed in the order of sending diff --git a/src/test/java/HttpEventCollector_Test.java b/src/test/java/HttpEventCollector_Test.java index 35a32920..4ad3188c 100644 --- a/src/test/java/HttpEventCollector_Test.java +++ b/src/test/java/HttpEventCollector_Test.java @@ -1,4 +1,4 @@ -/** +/* * @copyright * * Copyright 2013-2015 Splunk, Inc. @@ -30,7 +30,6 @@ import java.lang.reflect.*; import com.splunk.*; -import org.slf4j.*; public class HttpEventCollector_Test { public static void addPath(String s) throws Exception { @@ -82,7 +81,7 @@ private static int getEventsCount(String searchQuery) throws IOException, Interr } private static ServiceArgs serviceArgs; - private static String httpEventCollectorName = "functionalhttp"; + private static final String httpEventCollectorName = "functionalhttp"; private static String setupHttpEventCollector(boolean batching) throws Exception { TestUtil.enableHttpEventCollector(); @@ -121,7 +120,7 @@ public void TryToLogToSplunkWithDisabledHttpEventCollector() throws Exception { //modify the config file with the generated token String loggerName = "splunkLogger_disabled"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); if (batching) { userInputs.put("user_batch_interval", "200"); @@ -160,7 +159,7 @@ private boolean insertDataWithLoggerAndVerify(String token, String loggerType, i userInputs.put("user_batch_size_bytes", "12"); } - if (loggerType == "log4j") { + if (Objects.equals(loggerType, "log4j")) { String loggerName = "splunk.log4jInsertVerify"; userInputs.put("user_logger_name", loggerName); org.apache.logging.log4j.core.LoggerContext context = TestUtil.resetLog4j2Configuration("log4j2_template.xml", "log4j2.xml", userInputs); @@ -169,7 +168,7 @@ private boolean insertDataWithLoggerAndVerify(String token, String loggerType, i LOG4J.info(String.format("log4j message%d", i)); } } - if (loggerType == "logback") { + if (Objects.equals(loggerType, "logback")) { String loggerName = "logBackLogger"; userInputs.put("user_logger_name", loggerName); userInputs.put("user_defined_httpEventCollector_token", token); @@ -179,7 +178,7 @@ private boolean insertDataWithLoggerAndVerify(String token, String loggerType, i LOGBACK.info(String.format("logback message%d", i)); } } - if (loggerType == "javautil") { + if (Objects.equals(loggerType, "javautil")) { String loggerName = batching?"splunkLogger_batching":"splunkLogger_nobatching"; userInputs.put("user_logger_name", loggerName); TestUtil.resetJavaLoggingConfiguration("logging_template.properties", "logging.properties", userInputs); @@ -200,20 +199,17 @@ private boolean insertDataWithLoggerAndVerify(String token, String loggerType, i } private void LogToSplunk(boolean batching) throws Exception { - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - HttpEventCollectorErrorHandler.ServerErrorException serverErrorException = - (HttpEventCollectorErrorHandler.ServerErrorException) ex; - System.out.printf("ERROR: %s", ex.toString()); - Assert.assertTrue(false); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + HttpEventCollectorErrorHandler.ServerErrorException serverErrorException = + (HttpEventCollectorErrorHandler.ServerErrorException) ex; + System.out.printf("ERROR: %s", ex.toString()); + Assert.fail(); }); int expectedCounter = 2; System.out.printf("\tSetting up http event collector with %s ... ", batching ? "batching" : "no batching"); String token = setupHttpEventCollector(batching); System.out.printf("Set\n"); - Boolean testPassed = true; - testPassed &= insertDataWithLoggerAndVerify(token, "log4j", expectedCounter, batching); + boolean testPassed = insertDataWithLoggerAndVerify(token, "log4j", expectedCounter, batching); testPassed &= insertDataWithLoggerAndVerify(token, "logback", expectedCounter, batching); testPassed &= insertDataWithLoggerAndVerify(token, "javautil", expectedCounter, batching); Assert.assertTrue(testPassed); @@ -236,9 +232,9 @@ private void waitForIndexingToComplete(String query, int expectedCounter) throws } private static class DataSender implements Runnable { - private String threadName; + private final String threadName; public int eventsGenerated = 0, testDurationInSecs = 300; - java.util.logging.Logger logger; + private final java.util.logging.Logger logger; public DataSender(String threadName, int testDurationInSecs, java.util.logging.Logger logger) { this.threadName = threadName; @@ -249,7 +245,7 @@ public DataSender(String threadName, int testDurationInSecs, java.util.logging.L public void run() { Date dCurrent = new Date(); Date dEnd = new Date(); - dEnd.setTime(dCurrent.getTime() + testDurationInSecs * 1000); + dEnd.setTime(dCurrent.getTime() + testDurationInSecs * 1000L); while (dCurrent.before(dEnd)) { this.logger.info(String.format("javautil thread: %s, event: %d", this.threadName, eventsGenerated++)); try { @@ -265,20 +261,18 @@ public void run() { @Test public void ResendDataToSplunk() throws Exception { - HttpEventCollectorErrorHandler.onError(new HttpEventCollectorErrorHandler.ErrorCallback() { - public void error(final List data, final Exception ex) { - HttpEventCollectorErrorHandler.ServerErrorException serverErrorException = - (HttpEventCollectorErrorHandler.ServerErrorException) ex; - System.out.printf("ERROR: %s", ex.toString()); - Assert.assertTrue(false); - } + HttpEventCollectorErrorHandler.onError((data, ex) -> { + HttpEventCollectorErrorHandler.ServerErrorException serverErrorException = + (HttpEventCollectorErrorHandler.ServerErrorException) ex; + System.out.printf("ERROR: %s", ex.toString()); + Assert.fail(); }); boolean batching = false; System.out.printf("\tSetting up http event collector with %s ... ", batching ? "batching" : "no batching"); String token = setupHttpEventCollector(batching); System.out.printf("HTTP event collector fully set\n"); Service service = TestUtil.connectToSplunk(); - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_retries_on_error", "1000"); diff --git a/src/test/java/HttpLoggerStressTest.java b/src/test/java/HttpLoggerStressTest.java index 3f21ea03..961a9cb2 100644 --- a/src/test/java/HttpLoggerStressTest.java +++ b/src/test/java/HttpLoggerStressTest.java @@ -15,9 +15,9 @@ public class HttpLoggerStressTest { private static class DataSender implements Runnable { - private String threadName; + private final String threadName; public int eventsGenerated = 0, testDurationInSecs = 300; - Logger logger; + private final Logger logger; public DataSender(String threadName, int testDurationInSecs) { this.threadName = threadName; @@ -28,7 +28,7 @@ public DataSender(String threadName, int testDurationInSecs) { public void run() { Date dCurrent = new Date(); Date dEnd = new Date(); - dEnd.setTime(dCurrent.getTime() + testDurationInSecs * 1000); + dEnd.setTime(dCurrent.getTime() + testDurationInSecs * 1000L); while(dCurrent.before(dEnd)) { this.logger.info(String.format("Thread: %s, event: %d", this.threadName, eventsGenerated++)); dCurrent = new Date(); @@ -93,12 +93,12 @@ private static int getEventsCount(String searchQuery) throws IOException, Interr } private static ServiceArgs serviceArgs; - private static String httpEventCollectorName = "stressHttpEventCollector"; + private static final String httpEventCollectorName = "stressHttpEventCollector"; private static void setupHttpEventCollector() throws Exception { String token = TestUtil.createHttpEventCollectorToken(httpEventCollectorName); String loggerName = "splunkStressHttpLogger"; - HashMap userInputs = new HashMap(); + HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_batch_size_count", "1"); @@ -119,7 +119,7 @@ public void canSendEventUsingJavaLogging() throws Exception { Thread[] tList = new Thread[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++) { dsList[i] = new DataSender(String.format("Thread%s", i), testDurationInSecs); - tList[i] = new Thread(dsList[i]);; + tList[i] = new Thread(dsList[i]); } for (Thread t : tList) t.start(); @@ -149,7 +149,7 @@ public void canSendEventUsingJavaLogging() throws Exception { System.out.printf("\tCompleted wait for iteration %d\r\n", i); } } - Boolean testPassed = true; + boolean testPassed = true; for (int i = 0; i < numberOfThreads; i++) { String arguments = String.format("search Thread%d earliest=%d| stats count", i, startTime); eventCount = getEventsCount(arguments); diff --git a/src/test/java/JULFunctionalTest.java b/src/test/java/JULFunctionalTest.java index 54de6b02..17c31131 100644 --- a/src/test/java/JULFunctionalTest.java +++ b/src/test/java/JULFunctionalTest.java @@ -16,12 +16,6 @@ import org.junit.Assert; import org.junit.Test; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.ServerSocket; -import java.net.Socket; import java.util.logging.Logger; public class JULFunctionalTest { diff --git a/src/test/java/SplunkCimLogEventUnitTest.java b/src/test/java/SplunkCimLogEventUnitTest.java index 35407ec8..ed82a2c1 100644 --- a/src/test/java/SplunkCimLogEventUnitTest.java +++ b/src/test/java/SplunkCimLogEventUnitTest.java @@ -18,9 +18,6 @@ import org.junit.Assert; import org.junit.Test; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * Check that SplunkCimLogEvent produces what we expect it to. */ @@ -52,7 +49,7 @@ public void addFieldWithShortValue() { @Test public void addFieldWithIntValue() { SplunkCimLogEvent event = new SplunkCimLogEvent("name", "event-id"); - event.addField("key", (int)129); + event.addField("key", 129); Assert.assertEquals("\"name=name\" \"event_id=event-id\" \"key=129\"", event.toString()); } @@ -60,7 +57,7 @@ public void addFieldWithIntValue() { @Test public void addFieldWithLongValue() { SplunkCimLogEvent event = new SplunkCimLogEvent("name", "event-id"); - event.addField("key", (long)129L); + event.addField("key", 129L); Assert.assertEquals("\"name=name\" \"event_id=event-id\" \"key=129\"", event.toString()); } @@ -76,7 +73,7 @@ public void addFieldWithFloatValue() { @Test public void addFieldWithDoubleValue() { SplunkCimLogEvent event = new SplunkCimLogEvent("name", "event-id"); - event.addField("key", (double)129.32); + event.addField("key", 129.32); Assert.assertEquals("\"name=name\" \"event_id=event-id\" \"key=129.32\"", event.toString()); } diff --git a/src/test/java/TestFormatter.java b/src/test/java/TestFormatter.java index 945346ac..fa6405b1 100644 --- a/src/test/java/TestFormatter.java +++ b/src/test/java/TestFormatter.java @@ -13,7 +13,6 @@ * License for the specific language governing permissions and limitations * under the License. */ -import java.net.Inet4Address; import java.util.logging.Formatter; import java.util.logging.LogRecord; diff --git a/src/test/java/TestUtil.java b/src/test/java/TestUtil.java index d6c291a1..49ffb0f4 100644 --- a/src/test/java/TestUtil.java +++ b/src/test/java/TestUtil.java @@ -224,7 +224,7 @@ public static void disableHttpEventCollector() throws IOException { connectToSplunk(); //disable logging endpoint - Map args = new HashMap(); + Map args = new HashMap<>(); args.put("disabled", 1); ResponseMessage response = service.post("/servicesNS/admin/search/data/inputs/http/http", args); assert response.getStatus() == 200; @@ -237,7 +237,7 @@ public static void enableHttpEventCollector() throws IOException { connectToSplunk(); //enable logging endpoint - Map args = new HashMap(); + Map args = new HashMap<>(); args.put("disabled", 0); ResponseMessage response = service.post("/servicesNS/admin/search/data/inputs/http/http", args); assert response.getStatus() == 200; @@ -250,7 +250,7 @@ public static void enableHttpEventCollector() throws IOException { public static void disableHttpEventCollector(String httpEventCollectorName) throws IOException { connectToSplunk(); - Map args = new HashMap(); + Map args = new HashMap<>(); args.put("disabled", 1); ResponseMessage response = service.post(httpEventCollectorTokenEndpointPath + "/" + httpEventCollectorName, args); @@ -280,7 +280,7 @@ public static String updateConfigFile(String configFileTemplate, String configFi String match = FindUserInputConfiguration(lines.get(i)); if (!match.isEmpty()) { - if (userInputs.keySet().contains(match)) + if (userInputs.containsKey(match)) lines.set(i, lines.get(i).replace("%" + match + "%", userInputs.get(match))); else lines.set(i, ""); @@ -315,7 +315,7 @@ private static String FindUserInputConfiguration(String line) { /* create log4j2.xml and force log4j2 context manager to reload the configurations, return context and using this context to retrieve logger instead of using LogManager */ - public static org.apache.logging.log4j.core.LoggerContext resetLog4j2Configuration(String configFileTemplate, String configFile, HashMap userInputs) throws IOException, JoranException { + public static org.apache.logging.log4j.core.LoggerContext resetLog4j2Configuration(String configFileTemplate, String configFile, HashMap userInputs) throws IOException { String configFilePath = updateConfigFile(configFileTemplate, configFile, userInputs); org.apache.logging.log4j.core.LoggerContext context = new org.apache.logging.log4j.core.LoggerContext(userInputs.get("user_logger_name")); context.reconfigure(); @@ -340,7 +340,7 @@ public static void resetLogbackConfiguration(String configFileTemplate, String c /* create logging.property and force java logging manager to reload the configurations */ - public static void resetJavaLoggingConfiguration(String configFileTemplate, String configFile, HashMap userInputs) throws IOException, JoranException { + public static void resetJavaLoggingConfiguration(String configFileTemplate, String configFile, HashMap userInputs) throws IOException { String configFilePath = updateConfigFile(configFileTemplate, configFile, userInputs); FileInputStream configFileStream = new FileInputStream(configFilePath); LogManager.getLogManager().readConfiguration(configFileStream); @@ -369,10 +369,10 @@ public static void verifyOneAndOnlyOneEventSentToSplunk(String msg) throws IOExc break; } - resultsReader.close(); - resultsStream.close(); + Objects.requireNonNull(resultsReader, "resultsReader must not be null").close(); + Objects.requireNonNull(resultsStream, "resultsStream must not be null").close(); - Assert.assertTrue(eventCount == 1); + Assert.assertEquals(1, eventCount); } public static void verifyNoEventSentToSplunk(List msgs) throws IOException { @@ -399,10 +399,10 @@ public static void verifyNoEventSentToSplunk(List msgs) throws IOExcepti break; } - resultsReader.close(); - resultsStream.close(); + Objects.requireNonNull(resultsReader, "resultsReader must not be null").close(); + Objects.requireNonNull(resultsStream, "resultsStream must not be null").close(); - Assert.assertTrue(eventCount == 0); + Assert.assertEquals(0, eventCount); } /* @@ -444,8 +444,8 @@ public static void verifyEventsSentToSplunk(List msgs) throws IOExceptio Thread.sleep(5000); } - resultsReader.close(); - resultsStream.close(); + Objects.requireNonNull(resultsReader, "resultsReader must not be null").close(); + Objects.requireNonNull(resultsStream, "resultsStream must not be null").close(); Assert.assertEquals("Event search results did not match.", 1, eventCount); } @@ -470,7 +470,7 @@ private static InputStream searchJsonMessageEvent(final JsonObject jsonObject) { searchQuery.append(String.format(" | search \"message.%s\"=%s", jsonEntry.getKey(), jsonEntry.getValue())); } } - System.err.println(searchQuery.toString()); + System.err.println(searchQuery); return service.oneshotSearch(searchQuery.toString()); } @@ -481,7 +481,7 @@ public static void verifyEventsSentInOrder(String prefix, int totalEventsCount, long startTime = System.currentTimeMillis(); InputStream resultsStream = null; ResultsReaderXml resultsReader = null; - List results = new ArrayList(); + List results = new ArrayList<>(); while (System.currentTimeMillis() - startTime < 100 * 1000)/*wait for up to 30s*/ { results.clear(); String searchstr = "search index=" + index; @@ -496,8 +496,8 @@ public static void verifyEventsSentInOrder(String prefix, int totalEventsCount, break; } - resultsReader.close(); - resultsStream.close(); + Objects.requireNonNull(resultsReader, "resultsReader must not be null").close(); + Objects.requireNonNull(resultsStream, "resultsStream must not be null").close(); assert (results.size() == totalEventsCount) : String.format("expect: %d, actual: %d", totalEventsCount, results.size()); @@ -519,7 +519,7 @@ public static void verifyEventsSentInOrder(String prefix, int totalEventsCount, * @return the hash map */ public static HashMap buildUserInputMap(final String loggerName, final String token, final String sourceType, final String messageFormat) { - final HashMap userInputs = new HashMap(); + final HashMap userInputs = new HashMap<>(); userInputs.put("user_logger_name", loggerName); userInputs.put("user_httpEventCollector_token", token); userInputs.put("user_host", "host.example.com"); diff --git a/src/test/java/Util.java b/src/test/java/Util.java index 603897d3..208083e8 100644 --- a/src/test/java/Util.java +++ b/src/test/java/Util.java @@ -60,36 +60,33 @@ public static class StringContainer { public static StringContainer readLineFromPort(final int port, final int timeoutInMs) { final StringContainer container = new StringContainer(); - new Thread(new Runnable() { - @Override - public void run() { - ServerSocket serverSocket = null; - Socket socket = null; + new Thread(() -> { + ServerSocket serverSocket = null; + Socket socket = null; - try { - serverSocket = new ServerSocket(port); - serverSocket.setSoTimeout(timeoutInMs); - socket = serverSocket.accept(); - BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - container.value = in.readLine(); + try { + serverSocket = new ServerSocket(port); + serverSocket.setSoTimeout(timeoutInMs); + socket = serverSocket.accept(); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + container.value = in.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (socket != null) try { + socket.close(); } catch (IOException e) { e.printStackTrace(); - } finally { - if (socket != null) try { - socket.close(); - } catch (IOException e) { - e.printStackTrace(); - } + } - if (serverSocket != null) try { - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } + if (serverSocket != null) try { + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } - synchronized (container) { - container.notifyAll(); - } + synchronized (container) { + container.notifyAll(); } } }).start();