(DEFAULT_INET_ADDRESS_TTL_IN_NANOS) {
- @Nullable
- @Override
- protected InetAddress newObject() {
- try {
- return InetAddress.getByName(syslogServerHostname);
- } catch (UnknownHostException e) {
- throw new IllegalStateException(e);
- }
- }
- };
- }
-
- @Override
- public void setSyslogServerPort(int syslogServerPort) {
- this.syslogServerPort = syslogServerPort;
- }
-
- @Nullable
- public String getSyslogServerHostname() {
- InetAddress inetAddress = syslogServerHostnameReference.get();
- return inetAddress == null ? null : inetAddress.getHostName();
- }
-
- public int getSyslogServerPort() {
- return syslogServerPort;
- }
-
- @Override
- public String toString() {
- return getClass().getName() + "{" +
- "syslogServerHostname='" + this.getSyslogServerHostname() + '\'' +
- ", syslogServerPort='" + this.getSyslogServerPort() + '\'' +
- ", defaultAppName='" + defaultAppName + '\'' +
- ", defaultFacility=" + defaultFacility +
- ", defaultMessageHostname='" + defaultMessageHostname + '\'' +
- ", defaultSeverity=" + defaultSeverity +
- ", messageFormat=" + messageFormat +
- ", sendCounter=" + sendCounter +
- ", sendDurationInNanosCounter=" + sendDurationInNanosCounter +
- ", sendErrorCounter=" + sendErrorCounter +
- '}';
- }
-
- @Override
- public void close() throws IOException {
- this.datagramSocket.close();
- }
-}
diff --git a/src/main/java/com/cloudbees/syslog/util/CachingReference.java b/src/main/java/com/cloudbees/syslog/util/CachingReference.java
deleted file mode 100644
index 673452f..0000000
--- a/src/main/java/com/cloudbees/syslog/util/CachingReference.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2010-2013, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.util;
-
-import edu.umd.cs.findbugs.annotations.Nullable;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * Maintains a cached version of the {@code Object} that it holds and handle the renewal of this object upon expiration.
- *
- * Greatly inspired by the {@code CachedData} sample provided in the javadoc
- * of {@link java.util.concurrent.locks.ReentrantReadWriteLock}.
- *
- * {@code Object} is created implementing the {@link #newObject()} method.
- *
- *
- * Sample to get an {@code InetAddress} refreshed against a DNS every 10 seconds:
- *
- * CachingReference myRemoteServerAddress = new CachingReference<InetAddress>(10, TimeUnit.SECONDS) {
- * protected InetAddress newObject() {
- * try {
- * return InetAddress.getByName(myRemoteServerHostname);
- * } catch () {
- * throw new RuntimeException("Exception resolving '" + myRemoteServerHostname + "'", e);
- * }
- * }
- * }
- *
- *
- * @author Cyrille Le Clerc
- */
-public abstract class CachingReference {
- private final ReadWriteLock rwl = new ReentrantReadWriteLock();
- private long lastCreationInNanos;
- private long timeToLiveInNanos;
- private E object;
-
- public CachingReference(long timeToLiveInNanos) {
- this.timeToLiveInNanos = timeToLiveInNanos;
- }
-
- public CachingReference(long timeToLive, TimeUnit timeToLiveUnit) {
- this(TimeUnit.NANOSECONDS.convert(timeToLive, timeToLiveUnit));
- }
-
- /**
- * @return the newly created object.
- */
- @Nullable
- protected abstract E newObject();
-
- /**
- * @return the up to date version of the {@code Object} hold by this reference.
- */
- @Nullable
- public E get() {
- rwl.readLock().lock();
- try {
- if ((System.nanoTime() - lastCreationInNanos) > timeToLiveInNanos) {
- // Must release read lock before acquiring write lock
- rwl.readLock().unlock();
- rwl.writeLock().lock();
- try {
- // Recheck state because another thread might have
- // acquired write lock and changed state before we did.
- if ((System.nanoTime() - lastCreationInNanos) > timeToLiveInNanos) {
- object = newObject();
- lastCreationInNanos = System.nanoTime();
- }
- } finally {
- // Downgrade by acquiring read lock before releasing write lock
- rwl.readLock().lock();
- rwl.writeLock().unlock();
- }
- }
- return object;
- } finally {
- rwl.readLock().unlock();
- }
- }
-
- @Override
- public String toString() {
- return "CachingReference[" + this.object + "]";
- }
-}
diff --git a/src/main/java/com/cloudbees/syslog/util/ConcurrentDateFormat.java b/src/main/java/com/cloudbees/syslog/util/ConcurrentDateFormat.java
deleted file mode 100644
index c8b71c0..0000000
--- a/src/main/java/com/cloudbees/syslog/util/ConcurrentDateFormat.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2010-2014, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.util;
-
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-import java.util.TimeZone;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingDeque;
-
-/**
- * Thread safe date formatter.
- *
- * @author Cyrille Le Clerc
- */
-public class ConcurrentDateFormat {
- private final BlockingQueue dateFormats;
- private final String pattern;
- private final Locale locale;
- private final TimeZone timeZone;
-
- /**
- * Note: This constructor may not support all locales.
- * For full coverage, use the factory methods in the {@link java.text.DateFormat}
- * class.
- *
- * @param pattern the pattern describing the date and time pattern
- * @param locale the locale whose date pattern symbols should be used
- * @param timeZone the timezone used by the underlying calendar
- * @param maxCacheSize
- * @throws NullPointerException if the given pattern or locale is null
- * @throws IllegalArgumentException if the given pattern is invalid
- */
- public ConcurrentDateFormat(String pattern, Locale locale, TimeZone timeZone, int maxCacheSize) {
- this.dateFormats = new LinkedBlockingDeque<>(maxCacheSize);
- this.pattern = pattern;
- this.locale = locale;
- this.timeZone = timeZone;
- }
-
- /**
- * Formats a Date into a date/time string.
- *
- * @param date the time value to be formatted into a time string.
- * @return the formatted time string.
- */
- @NonNull
- @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
- public String format(@NonNull Date date) {
- SimpleDateFormat dateFormat = dateFormats.poll();
- if (dateFormat == null) {
- dateFormat = new SimpleDateFormat(pattern, locale);
- dateFormat.setTimeZone(timeZone);
- }
- try {
- return dateFormat.format(date);
- } finally {
- dateFormats.offer(dateFormat);
- }
- }
-
- @Override
- public String toString() {
- return "ConcurrentDateFormat[pattern=" + pattern + "]";
- }
-}
\ No newline at end of file
diff --git a/src/main/java/com/cloudbees/syslog/util/InternalLogger.java b/src/main/java/com/cloudbees/syslog/util/InternalLogger.java
deleted file mode 100644
index 14ae68a..0000000
--- a/src/main/java/com/cloudbees/syslog/util/InternalLogger.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright 2010-2014, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.util;
-
-import com.cloudbees.syslog.integration.jul.util.LevelHelper;
-
-import edu.umd.cs.findbugs.annotations.NonNull;
-import edu.umd.cs.findbugs.annotations.Nullable;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Don't use {@link java.util.logging.Logger} as this code can be used as an Handler for java.util.logging and we would then have an infinite loop.
- *
- * @author Cyrille Le Clerc
- */
-public class InternalLogger {
-
- private static Level level;
-
- static {
- try {
- level = LevelHelper.findLevel(System.getProperty("com.cloudbees.syslog.debugLevel"));
- } catch (RuntimeException e) {
- e.printStackTrace();
- }
- }
-
- public static InternalLogger getLogger(@NonNull String name) {
- return new InternalLogger(name);
- }
-
- public static InternalLogger getLogger(@NonNull Class> clazz) {
- return getLogger(clazz.getName());
- }
-
- public static Level getLevel() {
- return level;
- }
-
- public static void setLevel(Level level) {
- InternalLogger.level = level;
- }
-
- private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
- private final String name;
- /**
- * use java.util.logger to find the logger level if not specified by system property.
- */
- private final Logger julLogger;
-
- public InternalLogger(String name) {
- this.name = name;
- this.julLogger = Logger.getLogger(name);
- }
-
-
- public boolean isLoggable(Level level) {
- if (level == null)
- return false;
-
- if (this.level == null)
- return julLogger.isLoggable(level);
-
- return level.intValue() >= this.level.intValue();
- }
-
- public void finest(@Nullable String msg) {
- log(Level.FINEST, msg);
- }
-
- public void fine(@Nullable String msg) {
- log(Level.FINE, msg);
- }
-
- public void finer(@Nullable String msg) {
- log(Level.FINER, msg);
- }
-
- public void info(@Nullable String msg) {
- log(Level.INFO, msg);
- }
-
- public void log(@Nullable Level level, @Nullable String msg) {
- log(level, msg, null);
- }
-
- public void warn(@Nullable String msg) {
- log(Level.WARNING, msg);
- }
-
- public void warn(@Nullable String msg, @Nullable Throwable t) {
- log(Level.WARNING, msg, t);
- }
-
- /**
- * synchronize for the {@link java.text.SimpleDateFormat}.
- *
- * @param level
- * @param msg
- * @param t
- */
- public synchronized void log(@Nullable Level level, @Nullable String msg, @Nullable Throwable t) {
- if (!isLoggable(level))
- return;
- System.err.println(df.format(new Date()) + " [" + Thread.currentThread().getName() + "] " + name + " - " + level.getName() + ": " + msg);
- if (t != null)
- t.printStackTrace();
-
- }
-
-}
diff --git a/src/main/java/com/cloudbees/syslog/util/IoUtils.java b/src/main/java/com/cloudbees/syslog/util/IoUtils.java
deleted file mode 100644
index ec983fe..0000000
--- a/src/main/java/com/cloudbees/syslog/util/IoUtils.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright 2010-2014, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.util;
-
-import edu.umd.cs.findbugs.annotations.Nullable;
-import java.io.IOException;
-import java.io.Writer;
-import java.net.Socket;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class IoUtils {
- private IoUtils() {
-
- }
-
- public static void closeQuietly(@Nullable Socket socket) {
- try {
- if (socket != null && !socket.isClosed()) {
- socket.close();
- }
- } catch (Exception e) {
- }
- }
-
- /**
- * Note: does not {@link java.io.Writer#flush()} before closing.
- *
- * @param socket
- * @param writer
- */
- public static void closeQuietly(@Nullable Socket socket, @Nullable Writer writer) {
- if (writer != null) {
- try {
- writer.close();
- } catch (IOException e) {
-
- }
- }
- closeQuietly(socket);
- }
-}
diff --git a/src/main/java/com/cloudbees/syslog/Facility.java b/src/main/java/com/teragrep/rlo_14/Facility.java
similarity index 96%
rename from src/main/java/com/cloudbees/syslog/Facility.java
rename to src/main/java/com/teragrep/rlo_14/Facility.java
index cca22f8..d9425f2 100755
--- a/src/main/java/com/cloudbees/syslog/Facility.java
+++ b/src/main/java/com/teragrep/rlo_14/Facility.java
@@ -1,5 +1,6 @@
/*
* Copyright 2010-2014, CloudBees Inc.
+ * Copyright 2023, Suomen Kanuuna Oy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.cloudbees.syslog;
+package com.teragrep.rlo_14;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import edu.umd.cs.findbugs.annotations.Nullable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
@@ -27,6 +26,7 @@
* See RFC 5427 - Textual Conventions for Syslog Management for the {@link #label}.
*
* @author Cyrille Le Clerc
+ * @author StrongestNumber9
*/
public enum Facility implements Comparable {
@@ -145,10 +145,9 @@ public enum Facility implements Comparable {
/**
* Syslog facility textual code. Not {@code null}
*/
- @NonNull
private final String label;
- Facility(int numericalCode, @NonNull String label) {
+ Facility(int numericalCode, String label) {
this.numericalCode = numericalCode;
this.label = label;
}
@@ -158,7 +157,6 @@ public enum Facility implements Comparable {
* @return Syslog facility, not {@code null}
* @throws IllegalArgumentException the given numericalCode is not a valid Syslog facility numerical code
*/
- @NonNull
public static Facility fromNumericalCode(int numericalCode) throws IllegalArgumentException {
Facility facility = facilityFromNumericalCode.get(numericalCode);
if (facility == null) {
@@ -172,7 +170,6 @@ public static Facility fromNumericalCode(int numericalCode) throws IllegalArgume
* @return Syslog facility, {@code null} if given value is {@code null}
* @throws IllegalArgumentException the given value is not a valid Syslog facility textual code
*/
- @Nullable
public static Facility fromLabel(String label) throws IllegalArgumentException {
if (label == null || label.isEmpty())
return null;
diff --git a/src/main/java/com/cloudbees/syslog/SDElement.java b/src/main/java/com/teragrep/rlo_14/SDElement.java
similarity index 95%
rename from src/main/java/com/cloudbees/syslog/SDElement.java
rename to src/main/java/com/teragrep/rlo_14/SDElement.java
index 2b5ef24..0337850 100644
--- a/src/main/java/com/cloudbees/syslog/SDElement.java
+++ b/src/main/java/com/teragrep/rlo_14/SDElement.java
@@ -1,5 +1,6 @@
/*
* Copyright 2010-2014, CloudBees Inc.
+ * Copyright 2023, Suomen Kanuuna Oy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.cloudbees.syslog;
+package com.teragrep.rlo_14;
import java.io.Serializable;
import java.util.ArrayList;
@@ -122,6 +123,9 @@ private void validateSDID(String sdName) {
if (null == sdName) {
throw new IllegalArgumentException("SD-ID cannot be null");
}
+ if (sdName.isEmpty()) {
+ throw new IllegalArgumentException("SD-ID cannot be empty");
+ }
if (sdName.length() > 32) {
throw new IllegalArgumentException("SD-ID must be less than 32 characters: " + sdName);
}
diff --git a/src/main/java/com/cloudbees/syslog/SDParam.java b/src/main/java/com/teragrep/rlo_14/SDParam.java
similarity index 93%
rename from src/main/java/com/cloudbees/syslog/SDParam.java
rename to src/main/java/com/teragrep/rlo_14/SDParam.java
index de0527f..b84491a 100644
--- a/src/main/java/com/cloudbees/syslog/SDParam.java
+++ b/src/main/java/com/teragrep/rlo_14/SDParam.java
@@ -1,5 +1,6 @@
/*
* Copyright 2010-2014, CloudBees Inc.
+ * Copyright 2023, Suomen Kanuuna Oy.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.cloudbees.syslog;
+package com.teragrep.rlo_14;
import java.io.Serializable;
import java.util.Objects;
@@ -21,6 +22,7 @@
/**
*
* @author Brett Bergquist
+ * @author StrongestNumber9
*/
public class SDParam implements Serializable {
@@ -77,6 +79,9 @@ private void validateParamName(String sdName) {
if (null == sdName) {
throw new IllegalArgumentException("PARAM-NAME cannot be null");
}
+ if(sdName.isEmpty()) {
+ throw new IllegalArgumentException("PARAM-NAME cannot be empty");
+ }
if (sdName.length() > 32) {
throw new IllegalArgumentException("PARAM-NAME must be less than 32 characters: " + sdName);
}
diff --git a/src/main/java/com/cloudbees/syslog/Severity.java b/src/main/java/com/teragrep/rlo_14/Severity.java
similarity index 92%
rename from src/main/java/com/cloudbees/syslog/Severity.java
rename to src/main/java/com/teragrep/rlo_14/Severity.java
index e5d8bbf..c804ef2 100644
--- a/src/main/java/com/cloudbees/syslog/Severity.java
+++ b/src/main/java/com/teragrep/rlo_14/Severity.java
@@ -1,5 +1,6 @@
/*
* Copyright 2010-2014, CloudBees Inc.
+ * Copyright 2023, Suomen Kanuuna Oy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,10 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.cloudbees.syslog;
+package com.teragrep.rlo_14;
-import edu.umd.cs.findbugs.annotations.NonNull;
-import edu.umd.cs.findbugs.annotations.Nullable;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
@@ -25,6 +24,7 @@
* Syslog severity as defined in RFC 5424 - The Syslog Protocol.
*
* @author Cyrille Le Clerc
+ * @author StrongestNumber9
*/
public enum Severity {
/**
@@ -72,10 +72,9 @@ public enum Severity {
}
private final int numericalCode;
- @NonNull
private final String label;
- Severity(int numericalCode, @NonNull String label) {
+ Severity(int numericalCode, String label) {
this.numericalCode = numericalCode;
this.label = label;
}
@@ -98,8 +97,7 @@ public static Severity fromNumericalCode(int numericalCode) throws IllegalArgume
* @return Syslog severity, {@code null} if given value is {@code null}
* @throws IllegalArgumentException the given value is not a valid Syslog severity textual code
*/
- @Nullable
- public static Severity fromLabel(@Nullable String label) throws IllegalArgumentException {
+ public static Severity fromLabel(String label) throws IllegalArgumentException {
if (label == null || label.isEmpty())
return null;
@@ -120,7 +118,6 @@ public int numericalCode() {
/**
* Syslog severity textual code. Not {@code null}.
*/
- @NonNull
public String label() {
return label;
}
diff --git a/src/main/java/com/teragrep/rlo_14/SyslogMessage.java b/src/main/java/com/teragrep/rlo_14/SyslogMessage.java
new file mode 100755
index 0000000..5c27189
--- /dev/null
+++ b/src/main/java/com/teragrep/rlo_14/SyslogMessage.java
@@ -0,0 +1,292 @@
+/*
+ * Copyright 2010-2014, CloudBees Inc.
+ * Copyright 2023, Suomen Kanuuna Oy
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.teragrep.rlo_14;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.time.Instant;
+import java.util.*;
+
+/**
+ * Syslog message as defined in RFC 5424 - The Syslog Protocol.
+ *
+ * Also compatible with RFC-3164: The BSD syslog Protocol,
+ *
+ * @author Cyrille Le Clerc
+ * @author StrongestNumber9
+ */
+public class SyslogMessage {
+ public final static String SP = " ";
+ public final static String NILVALUE = "-";
+
+ private Facility facility;
+ private Severity severity;
+ private String timestamp = NILVALUE;
+ private String hostname = NILVALUE;
+ private String appName = NILVALUE;
+ private String procId = NILVALUE;
+ private String msgId = NILVALUE;
+ private Set sdElements;
+ private static final SimpleDateFormat rfc3339Formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
+
+ /**
+ * Use a {@link java.io.CharArrayWriter} instead of a {@link String} or a {@code char[]} because middlewares like
+ * Apache Tomcat use {@code CharArrayWriter} and it's convenient for pooling objects.
+ */
+ private String msg;
+
+ public Facility getFacility() {
+ return facility;
+ }
+
+ public void setFacility(Facility facility) {
+ this.facility = facility;
+ }
+
+ public SyslogMessage withFacility(Facility facility) {
+ this.facility = facility;
+ return this;
+ }
+
+ public Severity getSeverity() {
+ return severity;
+ }
+
+ public void setSeverity(Severity severity) {
+ this.severity = severity;
+ }
+
+ public SyslogMessage withSeverity(Severity severity) {
+ this.severity = severity;
+ return this;
+ }
+
+ public String getTimestamp() {
+ return timestamp;
+ }
+
+ public void setTimestamp(long timestamp) {
+ this.timestamp = Instant.ofEpochMilli(timestamp).toString();
+ }
+
+ public void setTimestamp(Instant timestamp) {
+ this.timestamp = timestamp.toString();
+ }
+
+ public void setTimestamp(String timestamp, boolean skipParse) {
+ if (skipParse) {
+ this.timestamp = timestamp;
+ }
+ else {
+ this.timestamp = Instant.parse(timestamp).toString();
+ }
+ }
+
+ public SyslogMessage withTimestamp(long timestamp) {
+ setTimestamp(timestamp);
+ return this;
+ }
+ public SyslogMessage withTimestamp(Instant timestamp) {
+ setTimestamp(timestamp);
+ return this;
+ }
+ public SyslogMessage withTimestamp(String timestamp) {
+ setTimestamp(timestamp, false);
+ return this;
+ }
+ public SyslogMessage withTimestamp(String timestamp, boolean skipParse) {
+ setTimestamp(timestamp, skipParse);
+ return this;
+ }
+
+ public String getHostname() {
+ return hostname;
+ }
+
+ public void setHostname(String hostname) {
+ this.hostname = hostname;
+ }
+
+ public SyslogMessage withHostname(String hostname) {
+ this.hostname = hostname;
+ return this;
+ }
+
+ public String getAppName() {
+ return appName;
+ }
+
+ public void setAppName(String appName) {
+ this.appName = appName;
+ }
+
+ public SyslogMessage withAppName(String appName) {
+ this.appName = appName;
+ return this;
+ }
+
+ public String getProcId() {
+ return procId;
+ }
+
+ public void setProcId(String procId) {
+ this.procId = procId;
+ }
+
+ public SyslogMessage withProcId(String procId) {
+ this.procId = procId;
+ return this;
+ }
+
+ public String getMsgId() {
+ return msgId;
+ }
+
+ public void setMsgId(String msgId) {
+ this.msgId = msgId;
+ }
+
+ public SyslogMessage withMsgId(String msgId) {
+ this.msgId = msgId;
+ return this;
+ }
+
+ public String getMsg() {
+ return msg;
+ }
+
+ public void setMsg(String msg) {
+ this.msg = msg;
+ }
+
+ public SyslogMessage withMsg(String msg) {
+ this.msg = msg;
+ return this;
+ }
+
+ public Set getSDElements() {
+ Set ssde = sdElements;
+ if (ssde == null) {
+ ssde = new LinkedHashSet<>(0);
+ }
+ return ssde;
+ }
+
+ public void setSDElements(Set ssde) {
+ this.sdElements = ssde;
+ }
+
+ public SyslogMessage withSDElement(SDElement sde) {
+ if (sdElements == null) {
+ sdElements = new LinkedHashSet<>();
+ }
+ sdElements.add(sde);
+ return this;
+ }
+
+ /**
+ * Generates an RFC-5424 message.
+ */
+ public String toRfc5424SyslogMessage() {
+
+ StringBuilder sw = new StringBuilder();
+ try {
+ toRfc5424SyslogMessage(sw);
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ return sw.toString();
+ }
+
+ /**
+ * Generates an RFC-5424 message.
+ *
+ * The priority is calculated by facility * 8 + severity, see
+ * RFC-5424, Section 6.2.1
+ */
+ public void toRfc5424SyslogMessage(StringBuilder out) throws IOException {
+ if(facility == null) {
+ throw new IllegalArgumentException("Facility must be set before constructing a message.");
+ }
+ if(severity == null) {
+ throw new IllegalArgumentException("Severity must be set before constructing a message");
+ }
+ int pri = facility.numericalCode() * 8 + severity.numericalCode();
+
+ out.append('<');
+ out.append(pri);
+ out.append('>');
+ out.append('1'); // version
+ out.append(SP);
+ out.append(timestamp); // message time
+ out.append(SP);
+ out.append(hostname); // emitting server hostname
+ out.append(SP);
+ out.append(appName);
+ out.append(SP);
+ out.append(procId);
+ out.append(SP);
+ out.append(msgId);
+ out.append(SP);
+ if(sdElements == null || sdElements.isEmpty()) {
+ out.append(NILVALUE);
+ }
+ else {
+ writeSDElements(out);
+ }
+ if (msg != null) {
+ out.append(SP);
+ out.append(msg);
+ }
+ }
+
+ protected void writeSDElements(StringBuilder out) throws IOException {
+ for (SDElement sde : sdElements) {
+ out.append("[");
+ out.append(sde.getSdID());
+ for (SDParam sdp : sde.getSdParams()) {
+ out.append(SP);
+ out.append(sdp.getParamName());
+ out.append('=');
+ out.append('"');
+ out.append(getEscapedParamValue(sdp.getParamValue()));
+ out.append('"');
+ }
+ out.append("]");
+ }
+ }
+
+ protected String getEscapedParamValue(String paramValue) {
+ StringBuilder sb = new StringBuilder(paramValue.length());
+
+ for (int i = 0; i < paramValue.length(); i++) {
+ char c = paramValue.charAt(i);
+ switch (c) {
+ // Falls through
+ case '"':
+ case '\\':
+ case ']':
+ sb.append('\\');
+ break;
+ default:
+ break;
+ }
+ sb.append(c);
+ }
+
+ return sb.toString();
+ }
+}
diff --git a/src/test/java/com/cloudbees/syslog/SyslogMessageTest.java b/src/test/java/com/cloudbees/syslog/SyslogMessageTest.java
deleted file mode 100755
index 6e5649e..0000000
--- a/src/test/java/com/cloudbees/syslog/SyslogMessageTest.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright 2010-2013, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog;
-
-import java.util.Calendar;
-import java.util.TimeZone;
-
-import org.junit.Test;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class SyslogMessageTest {
-
- @Test
- public void testRfc5425Format() {
- // GIVEN
- Calendar cal = Calendar.getInstance();
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
- cal.set(Calendar.MILLISECOND, 0);
-
- System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
- System.out.println(cal.getTimeInMillis());
-
-
- SyslogMessage message = new SyslogMessage()
- .withTimestamp(cal.getTimeInMillis())
- .withAppName("my_app")
- .withHostname("myserver.example.com")
- .withFacility(Facility.USER)
- .withSeverity(Severity.INFORMATIONAL)
- .withTimestamp(cal.getTimeInMillis())
- .withMsg("a syslog message");
-
- // WHEN
- String actual = message.toRfc5425SyslogMessage();
-
- // THEN
- String expected = "81 <14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - - a syslog message";
- assertThat(actual, is(expected));
- }
-
- @Test
- public void testRfc5424Format() {
-
- Calendar cal = Calendar.getInstance();
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
- cal.set(Calendar.MILLISECOND, 0);
-
- System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
- System.out.println(cal.getTimeInMillis());
-
-
- SyslogMessage message = new SyslogMessage()
- .withTimestamp(cal.getTimeInMillis())
- .withAppName("my_app")
- .withHostname("myserver.example.com")
- .withFacility(Facility.USER)
- .withSeverity(Severity.INFORMATIONAL)
- .withTimestamp(cal.getTimeInMillis())
- .withMsg("a syslog message");
-
- String actual = message.toRfc5424SyslogMessage();
- String expected = "<14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - - a syslog message";
-
- assertThat(actual, is(expected));
-
- }
-
- @Test
- public void testRfc5424FormatWithStructuredData() {
- Calendar cal = Calendar.getInstance();
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
- cal.set(Calendar.MILLISECOND, 0);
-
- System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
- System.out.println(cal.getTimeInMillis());
-
-
- SyslogMessage message = new SyslogMessage()
- .withTimestamp(cal.getTimeInMillis())
- .withAppName("my_app")
- .withHostname("myserver.example.com")
- .withFacility(Facility.USER)
- .withSeverity(Severity.INFORMATIONAL)
- .withTimestamp(cal.getTimeInMillis())
- .withMsg("a syslog message")
- .withSDElement(new SDElement("exampleSDID@32473", new SDParam("iut", "3"), new SDParam("eventSource", "Application"), new SDParam("eventID", "1011")));
-
- String actual = message.toRfc5424SyslogMessage();
- String expected = "<14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"] a syslog message";
-
- assertThat(actual, is(expected));
-
- message.withSDElement(new SDElement("examplePriority@32473", new SDParam("class", "high")));
- actual = message.toRfc5424SyslogMessage();
- expected = "<14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - [exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"][examplePriority@32473 class=\"high\"] a syslog message";
-
- assertThat(actual, is(expected));
- }
-
- @Test
- public void testRfc3164Format() {
-
- Calendar cal = Calendar.getInstance();
- cal.setTimeZone(TimeZone.getDefault());
- cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
- cal.set(Calendar.MILLISECOND, 0);
-
- System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
- System.out.println(cal.getTimeInMillis());
-
-
- SyslogMessage message = new SyslogMessage()
- .withTimestamp(cal.getTimeInMillis())
- .withAppName("my_app")
- .withHostname("myserver.example.com")
- .withFacility(Facility.USER)
- .withSeverity(Severity.INFORMATIONAL)
- .withTimestamp(cal.getTimeInMillis())
- .withMsg("a syslog message");
-
- String actual = message.toRfc3164SyslogMessage();
- String expected = "<14>Dec 05 10:30:05 myserver.example.com my_app: a syslog message";
-
- assertThat(actual, is(expected));
-
- }
-}
diff --git a/src/test/java/com/cloudbees/syslog/integration/jul/SyslogHandlerTest.java b/src/test/java/com/cloudbees/syslog/integration/jul/SyslogHandlerTest.java
deleted file mode 100644
index d46ca68..0000000
--- a/src/test/java/com/cloudbees/syslog/integration/jul/SyslogHandlerTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2010-2013 the original author or authors
- *
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- *
- */
-package com.cloudbees.syslog.integration.jul;
-
-import com.cloudbees.syslog.sender.UdpSyslogMessageSender;
-import org.junit.Test;
-
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class SyslogHandlerTest {
-
- @Test
- public void test(){
- Logger logger = Logger.getLogger(getClass().getName());
- logger.setLevel(Level.FINEST);
-
- UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender();
- SyslogHandler syslogHandler = new SyslogHandler(messageSender, Level.ALL, null);
-
- messageSender.setSyslogServerHostname("cloudbees1.papertrailapp.com");
- messageSender.setSyslogServerPort(18977);
-
- syslogHandler.setMessageHostname("mysecretkey");
- syslogHandler.setAppName("SyslogHandlerTest");
- logger.addHandler(syslogHandler);
-
- logger.fine("hello world 2");
- }
-}
diff --git a/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderLoadTest.java b/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderLoadTest.java
deleted file mode 100644
index 7f460c8..0000000
--- a/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderLoadTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright 2010-2014, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.sender;
-
-import com.cloudbees.syslog.Facility;
-import com.cloudbees.syslog.Severity;
-
-import java.io.IOException;
-import java.util.Random;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class TcpSyslogMessageSenderLoadTest {
-
- public static void main(String[] args) throws Exception {
- final int THREADS_COUNT = 5;
- final int ITERATION_COUNT = 100;
-
- ExecutorService executorService = Executors.newFixedThreadPool(THREADS_COUNT);
-
- final TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
- messageSender.setDefaultMessageHostname("mysecretkey");
- messageSender.setDefaultAppName("myapp");
- messageSender.setDefaultFacility(Facility.USER);
- messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
- messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
- // messageSender.setSyslogServerHostname("127.0.0.1");
- messageSender.setSyslogServerPort(46022);
- messageSender.setSsl(true);
-
- final AtomicInteger count = new AtomicInteger();
-
- final Random random = new Random();
-
- for (int i = 0; i < THREADS_COUNT; i++) {
- final String prefix = "thread-" + i + "msg-";
-
- Runnable command = new Runnable() {
- @Override
- public void run() {
- for (int j = 0; j < ITERATION_COUNT; j++) {
- try {
- messageSender.sendMessage(prefix + j);
- Thread.sleep(random.nextInt(3));
- } catch (IOException | InterruptedException e) {
- System.err.println("ERROR in " + prefix);
- e.printStackTrace();
- break;
- }
- }
- }
- };
-
- executorService.execute(command);
- }
-
- executorService.shutdown();
- executorService.awaitTermination(1, TimeUnit.MINUTES);
- System.out.println("sent " + messageSender.getSendCount() + " in " + messageSender.getSendDurationInMillis() + "ms");
- System.out.println("bye");
- }
-}
diff --git a/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderTest.java b/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderTest.java
deleted file mode 100644
index 0889109..0000000
--- a/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright 2010-2013, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.sender;
-
-import com.cloudbees.syslog.Facility;
-import com.cloudbees.syslog.MessageFormat;
-import com.cloudbees.syslog.Severity;
-import com.cloudbees.syslog.SyslogMessage;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.sql.Timestamp;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class TcpSyslogMessageSenderTest {
-
- // @Ignore
- @Test
- public void send() throws Exception {
- TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
- messageSender.setDefaultMessageHostname("mysecretkey");
- messageSender.setDefaultAppName("myapp");
- messageSender.setDefaultFacility(Facility.USER);
- messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
- messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
- messageSender.setSyslogServerPort(46022);
- messageSender.setMessageFormat(MessageFormat.RFC_3164);
- messageSender.setSsl(true);
- messageSender.sendMessage("unit test message over tcp éèà " + getClass() + " - " + new Timestamp(System.currentTimeMillis()));
- }
-
- @Ignore
- @Test
- public void send2() throws Exception {
-
- SyslogMessage msg = new SyslogMessage()
- .withAppName("my-app")
- .withFacility(Facility.USER)
- .withHostname("my-hostname")
- .withMsg("my message over tcp éèà " + new Timestamp(System.currentTimeMillis()))
- .withSeverity(Severity.INFORMATIONAL)
- .withTimestamp(System.currentTimeMillis());
-
- TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
- messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
- messageSender.setSyslogServerPort(46022);
- messageSender.setMessageFormat(MessageFormat.RFC_3164);
- messageSender.setSsl(true);
-
- System.out.println(msg.toSyslogMessage(messageSender.getMessageFormat()));
-
- messageSender.sendMessage(msg);
- }
-
-
- @Ignore
- @Test
- public void sendOverSSL() throws Exception {
-
- SyslogMessage msg = new SyslogMessage()
- .withAppName("my-app")
- .withFacility(Facility.USER)
- .withHostname("my-hostname")
- .withMsg("my message over tcp ssl éèà " + new Timestamp(System.currentTimeMillis()))
- .withSeverity(Severity.INFORMATIONAL)
- .withTimestamp(System.currentTimeMillis());
-
- TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
- messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
- messageSender.setSyslogServerPort(46022);
- messageSender.setMessageFormat(MessageFormat.RFC_3164);
- messageSender.setSsl(true);
-
- System.out.println(msg.toSyslogMessage(messageSender.getMessageFormat()));
-
- messageSender.sendMessage(msg);
- }
-
-
- /**
- * https://github.com/CloudBees-community/syslog-java-client/issues/19
- */
- @Test
- public void test_bug19_NullPointerException_In_ToString(){
- TcpSyslogMessageSender tcpSyslogMessageSender = new TcpSyslogMessageSender();
- tcpSyslogMessageSender.toString();
- }
-}
diff --git a/src/test/java/com/cloudbees/syslog/sender/UdpSyslogMessageSenderLoadTest.java b/src/test/java/com/cloudbees/syslog/sender/UdpSyslogMessageSenderLoadTest.java
deleted file mode 100644
index 0898504..0000000
--- a/src/test/java/com/cloudbees/syslog/sender/UdpSyslogMessageSenderLoadTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 2010-2014, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.sender;
-
-import com.cloudbees.syslog.Facility;
-import com.cloudbees.syslog.Severity;
-
-import java.io.IOException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class UdpSyslogMessageSenderLoadTest {
-
- public static void main(String[] args) throws Exception {
- final int THREADS_COUNT = 10;
- final int ITERATION_COUNT = 1000;
-
- ExecutorService executorService = Executors.newFixedThreadPool(THREADS_COUNT);
-
- final UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender();
- messageSender.setDefaultMessageHostname("mysecretkey");
- messageSender.setDefaultAppName("myapp");
- messageSender.setDefaultFacility(Facility.USER);
- messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
- messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
- // messageSender.setSyslogServerHostname("127.0.0.1");
- messageSender.setSyslogServerPort(46022);
-
- final AtomicInteger count = new AtomicInteger();
-
-
- for (int i = 0; i < THREADS_COUNT; i++) {
- final String prefix = "thread-" + i + "-udp-msg-";
-
- Runnable command = new Runnable() {
- @Override
- public void run() {
- for (int j = 0; j < ITERATION_COUNT; j++) {
- try {
- messageSender.sendMessage(prefix + j);
- } catch (IOException e) {
- System.err.println("ERROR in " + prefix);
- e.printStackTrace();
- break;
- }
- }
- }
- };
-
- executorService.execute(command);
- }
-
- executorService.shutdown();
- executorService.awaitTermination(1, TimeUnit.MINUTES);
- System.out.println("sent " + messageSender.getSendCount() + " in " + messageSender.getSendDurationInMillis() + "ms");
- System.out.println("bye");
- }
-}
diff --git a/src/test/java/com/cloudbees/syslog/sender/UpdSyslogMessageSenderTest.java b/src/test/java/com/cloudbees/syslog/sender/UpdSyslogMessageSenderTest.java
deleted file mode 100644
index 36e9978..0000000
--- a/src/test/java/com/cloudbees/syslog/sender/UpdSyslogMessageSenderTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright 2010-2013, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.sender;
-
-import com.cloudbees.syslog.Facility;
-import com.cloudbees.syslog.Severity;
-import org.junit.Test;
-
-import java.sql.Timestamp;
-
-/**
- * @author Cyrille Le Clerc
- */
-public class UpdSyslogMessageSenderTest {
-
- // @Ignore
- @Test
- public void send() throws Exception {
- UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender();
- messageSender.setDefaultMessageHostname("mysecretkey");
- messageSender.setDefaultAppName("myapp");
- messageSender.setDefaultFacility(Facility.USER);
- messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
- // messageSender.setSyslogServerHostname("cloudbees1.papertrailapp.com");
- messageSender.setSyslogServerHostname("127.0.0.1");
- messageSender.setSyslogServerPort(18977);
- messageSender.sendMessage("unit test message éèà " + getClass() + " - " + new Timestamp(System.currentTimeMillis()));
- }
-
-
-}
diff --git a/src/test/java/com/cloudbees/syslog/util/CachingReferenceTest.java b/src/test/java/com/cloudbees/syslog/util/CachingReferenceTest.java
deleted file mode 100644
index 471f6e2..0000000
--- a/src/test/java/com/cloudbees/syslog/util/CachingReferenceTest.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2010-2013, CloudBees Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.cloudbees.syslog.util;
-
-import org.hamcrest.Matchers;
-import org.junit.Test;
-
-import edu.umd.cs.findbugs.annotations.Nullable;
-import java.util.concurrent.TimeUnit;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-
-public class CachingReferenceTest {
- /**
- * Test that the locks are properly released.
- */
- @Test
- public void test_return_value() {
-
- CachingReference cachingReference = new CachingReference(5, TimeUnit.SECONDS) {
- @Nullable
- @Override
- protected String newObject() {
- return "value";
- }
- };
-
- String actual = cachingReference.get();
- assertThat(actual, Matchers.equalTo("value"));
- }
-
- /**
- * Test that the locks are properly released.
- */
- @Test(expected = MyRuntimeException.class)
- public void test_throw_exception_in_get_object() {
-
- CachingReference cachingReference = new CachingReference(5, TimeUnit.SECONDS) {
- @Nullable
- @Override
- protected String newObject() {
- throw new MyRuntimeException();
- }
- };
-
- cachingReference.get();
- }
-
-
- private static class MyRuntimeException extends RuntimeException {
- public MyRuntimeException() {
- super();
- }
-
- public MyRuntimeException(Throwable cause) {
- super(cause);
- }
-
- public MyRuntimeException(String message) {
- super(message);
- }
-
- public MyRuntimeException(String message, Throwable cause) {
- super(message, cause);
- }
-
- protected MyRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
- super(message, cause, enableSuppression, writableStackTrace);
- }
- }
-}
\ No newline at end of file
diff --git a/src/test/java/com/teragrep/rlo_14/BenchmarkTest.java b/src/test/java/com/teragrep/rlo_14/BenchmarkTest.java
new file mode 100644
index 0000000..c9e9ab8
--- /dev/null
+++ b/src/test/java/com/teragrep/rlo_14/BenchmarkTest.java
@@ -0,0 +1,93 @@
+/*
+ Java RFC5424 Syslog Formatter RLO_14
+ Copyright (C) 2023 Suomen Kanuuna Oy
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+package com.teragrep.rlo_14;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Warmup;
+
+import java.time.Instant;
+
+public class BenchmarkTest {
+ public static void main(String[] args) throws Exception {
+ org.openjdk.jmh.Main.main(args);
+ }
+
+ @Benchmark
+ @Fork(value=1, warmups=1)
+ @Warmup(iterations=1, time=5)
+ @Measurement(iterations=5, time=5)
+ public void testBenchmarkStringTimestamp() {
+ String message = new SyslogMessage()
+ .withTimestamp("2023-06-14T16:37:00.000Z")
+ .withAppName("my_app")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("a syslog message")
+ .toRfc5424SyslogMessage();
+ }
+
+ @Benchmark
+ @Fork(value=1, warmups=1)
+ @Warmup(iterations=1, time=5)
+ @Measurement(iterations=5, time=5)
+ public void testBenchmarkStringTimestampSkipParse() {
+ String message = new SyslogMessage()
+ .withTimestamp("2023-06-14T16:37:00.000Z", true)
+ .withAppName("my_app")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("a syslog message")
+ .toRfc5424SyslogMessage();
+ }
+
+ @Benchmark
+ @Fork(value=1, warmups=1)
+ @Warmup(iterations=1, time=5)
+ @Measurement(iterations=5, time=5)
+ public void testBenchmarkLongTimestamp() {
+ long time = Instant.now().toEpochMilli();
+ String message = new SyslogMessage()
+ .withTimestamp(time)
+ .withAppName("my_app")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("a syslog message")
+ .toRfc5424SyslogMessage();
+ }
+
+ @Benchmark
+ @Fork(value=1, warmups=1)
+ @Warmup(iterations=1, time=5)
+ @Measurement(iterations=5, time=5)
+ public void testBenchmarkInstantTimestamp() {
+ Instant time = Instant.now();
+ String message = new SyslogMessage()
+ .withTimestamp(time)
+ .withAppName("my_app")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("a syslog message")
+ .toRfc5424SyslogMessage();
+ }
+}
diff --git a/src/test/java/com/teragrep/rlo_14/FormatTest.java b/src/test/java/com/teragrep/rlo_14/FormatTest.java
new file mode 100755
index 0000000..8dfdf0c
--- /dev/null
+++ b/src/test/java/com/teragrep/rlo_14/FormatTest.java
@@ -0,0 +1,160 @@
+/*
+ Java RFC5424 Syslog Formatter RLO_14
+ Copyright (C) 2023 Suomen Kanuuna Oy
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+package com.teragrep.rlo_14;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+
+public class FormatTest {
+ @Test
+ public void testMessageWithLongDate() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testMessageWithLongDateFrac() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.123Z");
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00.123Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testMessageWithStringDate() {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp("2023-06-14T16:37:00.000Z")
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testMessageWithStringDateFrac() {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp("2023-06-14T16:37:00.123Z")
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00.123Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testMessageWithStringDateSkipFormat() {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp("2023-06-14T16:37:00.000Z", true)
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00.000Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testMessageWithInstantDate() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time)
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testMessageWithInstantDateFrac() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.123Z");
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time)
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00.123Z localhost example - - - test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testStructuredData() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "event_version@48577",
+ new SDParam("major", "1"),
+ new SDParam("minor", "0"),
+ new SDParam("version_source", "source")
+ )
+ );
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00Z localhost example - - [event_version@48577 major=\"1\" minor=\"0\" version_source=\"source\"] test message";
+ Assertions.assertEquals(expected, actual);
+ message.withSDElement(
+ new SDElement(
+ "session@48577",
+ new SDParam("state", "new"),
+ new SDParam("counter", "1")
+ )
+ );
+ actual = message.toRfc5424SyslogMessage();
+ expected = "<14>1 2023-06-14T16:37:00Z localhost example - - [event_version@48577 major=\"1\" minor=\"0\" version_source=\"source\"][session@48577 state=\"new\" counter=\"1\"] test message";
+ Assertions.assertEquals(expected, actual);
+ }
+}
diff --git a/src/test/java/com/teragrep/rlo_14/MissingFieldsTest.java b/src/test/java/com/teragrep/rlo_14/MissingFieldsTest.java
new file mode 100644
index 0000000..5a90f27
--- /dev/null
+++ b/src/test/java/com/teragrep/rlo_14/MissingFieldsTest.java
@@ -0,0 +1,64 @@
+/*
+ Java RFC5424 Syslog Formatter RLO_14
+ Copyright (C) 2023 Suomen Kanuuna Oy
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+package com.teragrep.rlo_14;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class MissingFieldsTest {
+ @Test
+ public void missingFacilityTest() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ String message = new SyslogMessage().withSeverity(Severity.INFORMATIONAL).toRfc5424SyslogMessage();
+ }
+ );
+ }
+
+ @Test
+ public void missingSeverityTest() {
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ String message = new SyslogMessage().withFacility(Facility.USER).toRfc5424SyslogMessage();
+ }
+ );
+ }
+
+ @Test
+ public void missingRestFieldsTest() {
+ SyslogMessage message = new SyslogMessage()
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL);
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 - - - - - -";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void missingRestFieldsTestWithMsg() {
+ SyslogMessage message = new SyslogMessage()
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("Test message");
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 - - - - - - Test message";
+ Assertions.assertEquals(expected, actual);
+ }
+}
diff --git a/src/test/java/com/teragrep/rlo_14/SDElementTest.java b/src/test/java/com/teragrep/rlo_14/SDElementTest.java
new file mode 100644
index 0000000..817597c
--- /dev/null
+++ b/src/test/java/com/teragrep/rlo_14/SDElementTest.java
@@ -0,0 +1,232 @@
+/*
+ Java RFC5424 Syslog Formatter RLO_14
+ Copyright (C) 2023 Suomen Kanuuna Oy
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+package com.teragrep.rlo_14;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+public class SDElementTest {
+ @Test
+ public void testReservedSDElement() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "notReserved",
+ new SDParam("mySD", "value=\"1\"")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testEmptySDElement() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "",
+ new SDParam("mySD", "value=\"1\"")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testNullSDElement() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ null,
+ new SDParam("mySD", "value=\"1\"")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testEmptySDElementName() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "",
+ new SDParam("test", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDElementNameTooLong() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "ThisIsLongerThan32CharactersLongSD",
+ new SDParam("test", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDElementSpace() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "This is invalid",
+ new SDParam("test", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDElementEquals() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "this=invalid",
+ new SDParam("test", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDElementBracketClose() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "this]notgood",
+ new SDParam("test", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDElementQuote() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "this\"notgood",
+ new SDParam("test", "1")
+ )
+ );
+ }
+ );
+ }
+
+}
\ No newline at end of file
diff --git a/src/test/java/com/teragrep/rlo_14/SDParamTest.java b/src/test/java/com/teragrep/rlo_14/SDParamTest.java
new file mode 100644
index 0000000..0e4d124
--- /dev/null
+++ b/src/test/java/com/teragrep/rlo_14/SDParamTest.java
@@ -0,0 +1,207 @@
+package com.teragrep.rlo_14;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+
+/*
+ Java RFC5424 Syslog Formatter RLO_14
+ Copyright (C) 2023 Suomen Kanuuna Oy
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+public class SDParamTest {
+ @Test
+ public void testSDParamEscape() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("mySD", "value=\"\\[1]\\\"")
+ )
+ );
+ String actual = message.toRfc5424SyslogMessage();
+ String expected = "<14>1 2023-06-14T16:37:00Z localhost example - - [exampleSD@48577 mySD=\"value=\\\"\\\\[1\\]\\\\\\\"\"] test message";
+ Assertions.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testEmptySDParamName() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testNullSDParamName() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam(null, "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDParamNameTooLong() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("ThisIsLongerThan32CharactersLongParam", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDSpace() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("not good", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDEquals() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("not=good", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDBracketClose() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("not]good", "1")
+ )
+ );
+ }
+ );
+ }
+
+ @Test
+ public void testInvalidSDQuote() {
+ Instant time = Instant.parse("2023-06-14T16:37:00.000Z");
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ SyslogMessage message = new SyslogMessage()
+ .withTimestamp(time.toEpochMilli())
+ .withAppName("example")
+ .withHostname("localhost")
+ .withFacility(Facility.USER)
+ .withSeverity(Severity.INFORMATIONAL)
+ .withMsg("test message")
+ .withSDElement(
+ new SDElement(
+ "exampleSD@48577",
+ new SDParam("not\"good", "1")
+ )
+ );
+ }
+ );
+ }
+}
\ No newline at end of file