From 256facf9f8116d56892d7ef7582c866d66456b2f Mon Sep 17 00:00:00 2001 From: Strongest Number 9 <16169054+StrongestNumber9@users.noreply.github.com> Date: Thu, 15 Jun 2023 15:12:38 +0300 Subject: [PATCH] Cleanup (#1) * Major cleanup * Update readme, to adoc * Remove MessageFormat * Fixes copypaste mistake * Optimize writing sd params, use stringbuilder where possible * Fixes getTimestamp * Fixes readme, developer info * Fixes license on BenchmarkTest * Adds copyright to pom * Fixes legacy double conversion * Do not support date anymore, use Instant for timestamps, rewrite format test * Another hashset to linkedhashset * README fixes * Use java benchmarking harness * Add copyright, author headers on modified files * Adds github workflow * Adds tests for SD and missing fields, fixes boundaries to align with rfc5424 specs --- .github/dependabot.yml | 12 - .github/workflows/upload_release.yaml | 51 ++ .gitignore | 15 - .mvn/wrapper/MavenWrapperDownloader.java | 110 ---- .mvn/wrapper/maven-wrapper.properties | 18 - Jenkinsfile | 10 - README.adoc | 96 +++ README.md | 152 ----- mvnw | 316 ---------- mvnw.cmd | 188 ------ pom.xml | 552 ++++++++---------- .../com/cloudbees/syslog/MessageFormat.java | 36 -- .../com/cloudbees/syslog/SyslogMessage.java | 450 -------------- .../integration/jul/AbstractHandler.java | 118 ---- .../syslog/integration/jul/SyslogHandler.java | 176 ------ .../jul/SyslogMessageFormatter.java | 50 -- .../integration/jul/util/LevelHelper.java | 97 --- .../jul/util/LogManagerHelper.java | 177 ------ .../sender/AbstractSyslogMessageSender.java | 175 ------ .../syslog/sender/SyslogMessageSender.java | 69 --- .../syslog/sender/TcpSyslogMessageSender.java | 293 ---------- .../syslog/sender/UdpSyslogMessageSender.java | 154 ----- .../syslog/util/CachingReference.java | 101 ---- .../syslog/util/ConcurrentDateFormat.java | 83 --- .../cloudbees/syslog/util/InternalLogger.java | 128 ---- .../com/cloudbees/syslog/util/IoUtils.java | 56 -- .../syslog => teragrep/rlo_14}/Facility.java | 11 +- .../syslog => teragrep/rlo_14}/SDElement.java | 6 +- .../syslog => teragrep/rlo_14}/SDParam.java | 7 +- .../syslog => teragrep/rlo_14}/Severity.java | 13 +- .../com/teragrep/rlo_14/SyslogMessage.java | 292 +++++++++ .../cloudbees/syslog/SyslogMessageTest.java | 148 ----- .../integration/jul/SyslogHandlerTest.java | 54 -- .../TcpSyslogMessageSenderLoadTest.java | 80 --- .../sender/TcpSyslogMessageSenderTest.java | 103 ---- .../UdpSyslogMessageSenderLoadTest.java | 76 --- .../sender/UpdSyslogMessageSenderTest.java | 44 -- .../syslog/util/CachingReferenceTest.java | 84 --- .../com/teragrep/rlo_14/BenchmarkTest.java | 93 +++ .../java/com/teragrep/rlo_14/FormatTest.java | 160 +++++ .../teragrep/rlo_14/MissingFieldsTest.java | 64 ++ .../com/teragrep/rlo_14/SDElementTest.java | 232 ++++++++ .../java/com/teragrep/rlo_14/SDParamTest.java | 207 +++++++ 43 files changed, 1461 insertions(+), 3896 deletions(-) delete mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/upload_release.yaml delete mode 100755 .mvn/wrapper/MavenWrapperDownloader.java delete mode 100755 .mvn/wrapper/maven-wrapper.properties delete mode 100644 Jenkinsfile create mode 100644 README.adoc delete mode 100644 README.md delete mode 100755 mvnw delete mode 100644 mvnw.cmd delete mode 100644 src/main/java/com/cloudbees/syslog/MessageFormat.java delete mode 100755 src/main/java/com/cloudbees/syslog/SyslogMessage.java delete mode 100644 src/main/java/com/cloudbees/syslog/integration/jul/AbstractHandler.java delete mode 100644 src/main/java/com/cloudbees/syslog/integration/jul/SyslogHandler.java delete mode 100644 src/main/java/com/cloudbees/syslog/integration/jul/SyslogMessageFormatter.java delete mode 100644 src/main/java/com/cloudbees/syslog/integration/jul/util/LevelHelper.java delete mode 100644 src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java delete mode 100644 src/main/java/com/cloudbees/syslog/sender/AbstractSyslogMessageSender.java delete mode 100644 src/main/java/com/cloudbees/syslog/sender/SyslogMessageSender.java delete mode 100644 src/main/java/com/cloudbees/syslog/sender/TcpSyslogMessageSender.java delete mode 100644 src/main/java/com/cloudbees/syslog/sender/UdpSyslogMessageSender.java delete mode 100644 src/main/java/com/cloudbees/syslog/util/CachingReference.java delete mode 100644 src/main/java/com/cloudbees/syslog/util/ConcurrentDateFormat.java delete mode 100644 src/main/java/com/cloudbees/syslog/util/InternalLogger.java delete mode 100644 src/main/java/com/cloudbees/syslog/util/IoUtils.java rename src/main/java/com/{cloudbees/syslog => teragrep/rlo_14}/Facility.java (96%) rename src/main/java/com/{cloudbees/syslog => teragrep/rlo_14}/SDElement.java (95%) rename src/main/java/com/{cloudbees/syslog => teragrep/rlo_14}/SDParam.java (93%) rename src/main/java/com/{cloudbees/syslog => teragrep/rlo_14}/Severity.java (92%) create mode 100755 src/main/java/com/teragrep/rlo_14/SyslogMessage.java delete mode 100755 src/test/java/com/cloudbees/syslog/SyslogMessageTest.java delete mode 100644 src/test/java/com/cloudbees/syslog/integration/jul/SyslogHandlerTest.java delete mode 100644 src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderLoadTest.java delete mode 100644 src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderTest.java delete mode 100644 src/test/java/com/cloudbees/syslog/sender/UdpSyslogMessageSenderLoadTest.java delete mode 100644 src/test/java/com/cloudbees/syslog/sender/UpdSyslogMessageSenderTest.java delete mode 100644 src/test/java/com/cloudbees/syslog/util/CachingReferenceTest.java create mode 100644 src/test/java/com/teragrep/rlo_14/BenchmarkTest.java create mode 100755 src/test/java/com/teragrep/rlo_14/FormatTest.java create mode 100644 src/test/java/com/teragrep/rlo_14/MissingFieldsTest.java create mode 100644 src/test/java/com/teragrep/rlo_14/SDElementTest.java create mode 100644 src/test/java/com/teragrep/rlo_14/SDParamTest.java diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 1b90aec..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,12 +0,0 @@ -# https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates - -version: 2 -updates: - - package-ecosystem: "maven" - directory: "/" - schedule: - interval: "weekly" - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" diff --git a/.github/workflows/upload_release.yaml b/.github/workflows/upload_release.yaml new file mode 100644 index 0000000..44b8dc0 --- /dev/null +++ b/.github/workflows/upload_release.yaml @@ -0,0 +1,51 @@ +name: Upload Release + +on: + release: + types: published + +jobs: + upload: + name: Upload + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Cache Local Maven Repository + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + + - name: Setup Maven Central + uses: actions/setup-java@v2 + with: + java-version: 8.0.292+10 + distribution: 'adopt' + + server-id: ossrh + server-username: MAVEN_CENTRAL_USERNAME + server-password: MAVEN_CENTRAL_TOKEN + + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE + + - name: Publish to Maven Central + run: mvn --batch-mode -Drevision=${{ github.event.release.tag_name }} -Dsha1= -Dchangelist= clean deploy -Ppublish-maven-central + env: + MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + MAVEN_CENTRAL_TOKEN: ${{ secrets.MAVEN_CENTRAL_TOKEN }} + + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + - name: Setup GitHub Packages + uses: actions/setup-java@v2 + with: + java-version: 8.0.292+10 + distribution: 'adopt' + + - name: Publish to GitHub Packages + run: mvn --batch-mode -Drevision=${{ github.event.release.tag_name }} -Dsha1= -Dchangelist= clean deploy -Ppublish-github-packages + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index 08dd799..689f474 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,6 @@ target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties -.mvn/wrapper/maven-wrapper.jar - -# IntelliJ IDEA project files *.iml *.iws *.ipr .idea - -# Eclipse project files -.settings -.classpath -.project diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100755 index fa4f7b4..0000000 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,110 +0,0 @@ -/* -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you 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. -*/ - -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = - "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: : " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties deleted file mode 100755 index db95c13..0000000 --- a/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,18 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.5/apache-maven-3.8.5-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index e283569..0000000 --- a/Jenkinsfile +++ /dev/null @@ -1,10 +0,0 @@ -/* - * While this is not a plugin, it is much simpler to reuse the pipeline code for CI. This allows for - * easy Linux/Windows testing and produces incrementals. The only feature that relates to plugins is - * allowing one to test against multiple Jenkins versions. - */ -buildPlugin(useContainerAgent: true, configurations: [ - [ platform: 'linux', jdk: '8' ], - [ platform: 'linux', jdk: '11' ], - [ platform: 'windows', jdk: '11' ] -]) diff --git a/README.adoc b/README.adoc new file mode 100644 index 0000000..f9e8095 --- /dev/null +++ b/README.adoc @@ -0,0 +1,96 @@ += Java RFC5424 Syslog Formatter + +== Description + +Java RFC5424 formatter library + +== Using the Syslog Java Client with Maven + +Add the following dependency in your pom.xml: + +[source,xml] +---- + + com.teragrep + rlo_14 + 1.0.0 + +---- + +== Usage + +Sourcing timestamp from long +[source,java] +---- +Instant time = Instant.now(); +SyslogMessage message = new SyslogMessage() + .withTimestamp(time.toEpochMilli()) + .withAppName("my_app") + .withHostname("localhost") + .withFacility(Facility.USER) + .withSeverity(Severity.INFORMATIONAL) + .withMsg("a syslog message"); +String actual = message.toRfc5424SyslogMessage(); +---- + +Sourcing timestamp from Instant +[source,java] +---- +Instant time = Instant.now(); +SyslogMessage message = new SyslogMessage() + .withTimestamp(time) + .withAppName("my_app") + .withHostname("localhost") + .withFacility(Facility.USER) + .withSeverity(Severity.INFORMATIONAL) + .withMsg("a syslog message"); +String actual = message.toRfc5424SyslogMessage(); +---- + +Sourcing timestamp from string (parsed and validated) +[source,java] +---- +SyslogMessage 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"); +String actual = message.toRfc5424SyslogMessage(); +---- + +Sourcing timestamp from string (no validation, useful when you know you have correct format) +[source,java] +---- +SyslogMessage 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"); +String actual = message.toRfc5424SyslogMessage(); +---- + +Adding structured data + +[source,java] +---- +SyslogMessage 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") + .withSDElement( + new SDElement( + "event_version@48577", + new SDParam("major", "1"), + new SDParam("minor", "0"), + new SDParam("version_source", "source") + ) + ); +String actual = message.toRfc5424SyslogMessage(); +---- \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 18d6786..0000000 --- a/README.md +++ /dev/null @@ -1,152 +0,0 @@ -# Syslog Java Client - -## Description - -Client library written in Java to send messages to a Syslog server. - - * `SyslogMessageSender`: send messages to a Syslog Server. Support implementations - * `UdpSyslogMessageSender`: [RFC 3164 - The BSD syslog Protocol](http://tools.ietf.org/html/rfc3164) and [RFC 5426 - Transmission of Syslog Messages over UDP](http://tools.ietf.org/html/rfc5426) - * `TcpSyslogMessageSender`: [RFC 6587 - Transmission of Syslog Messages over TCP](http://tools.ietf.org/html/rfc5426) (including SSL support) - * `TcpSyslogMessageSender`: [RFC 5425 - Transport Layer Security (TLS) Transport Mapping for Syslog](http://tools.ietf.org/html/rfc5426) (including SSL support) - * `com.cloudbees.syslog.integration.jul.SyslogHandler`: java.util.logging handler to output log messages to a Syslog server. - -## Release Notes and downloads - -See https://github.com/CloudBees-community/syslog-java-client/releases/ - -## Using the Syslog Java Client with Maven - -Add the following dependency in your pom.xml: - -```xml - - com.cloudbees - syslog-java-client - 1.1.7 - -``` - -## Sample UDP sender using RFC 3164 - -```java -import com.cloudbees.syslog.Facility; -import com.cloudbees.syslog.MessageFormat; -import com.cloudbees.syslog.Severity; -import com.cloudbees.syslog.sender.UdpSyslogMessageSender; - -... - -// Initialise sender -UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender(); -messageSender.setDefaultMessageHostname("myhostname"); // some syslog cloud services may use this field to transmit a secret key -messageSender.setDefaultAppName("myapp"); -messageSender.setDefaultFacility(Facility.USER); -messageSender.setDefaultSeverity(Severity.INFORMATIONAL); -messageSender.setSyslogServerHostname("127.0.0.1"); -// syslog udp usually uses port 514 as per https://tools.ietf.org/html/rfc3164#page-5 -messageSender.setSyslogServerPort(514); -messageSender.setMessageFormat(MessageFormat.RFC_3164); // optional, default is RFC 3164 - -// send a Syslog message -messageSender.sendMessage("This is a test message"); -``` - -## Sample UDP sender using RFC 5424 - -```java -import com.cloudbees.syslog.Facility; -import com.cloudbees.syslog.MessageFormat; -import com.cloudbees.syslog.Severity; -import com.cloudbees.syslog.sender.UdpSyslogMessageSender; - -... - -// Initialise sender -UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender(); -messageSender.setDefaultMessageHostname("myhostname"); // some syslog cloud services may use this field to transmit a secret key -messageSender.setDefaultAppName("myapp"); -messageSender.setDefaultFacility(Facility.USER); -messageSender.setDefaultSeverity(Severity.INFORMATIONAL); -messageSender.setSyslogServerHostname("127.0.0.1"); -messageSender.setSyslogServerPort(1234); -messageSender.setMessageFormat(MessageFormat.RFC_5424); - -// send a Syslog message -messageSender.sendMessage("This is a test message"); -``` - -## Sample TCP sender using RFC 3164 - -```java -import com.cloudbees.syslog.Facility; -import com.cloudbees.syslog.MessageFormat; -import com.cloudbees.syslog.Severity; -import com.cloudbees.syslog.sender.TcpSyslogMessageSender; - -... - -// Initialise sender -TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender(); -messageSender.setDefaultMessageHostname("myhostname"); // some syslog cloud services may use this field to transmit a secret key -messageSender.setDefaultAppName("myapp"); -messageSender.setDefaultFacility(Facility.USER); -messageSender.setDefaultSeverity(Severity.INFORMATIONAL); -messageSender.setSyslogServerHostname("127.0.0.1"); -messageSender.setSyslogServerPort(1234); -messageSender.setMessageFormat(MessageFormat.RFC_3164); // optional, default is RFC 3164 -messageSender.setSsl(false); - -// send a Syslog message -messageSender.sendMessage("This is a test message"); -``` - -## Sample TCP over SSL sender using RFC 3164 - -```java -import com.cloudbees.syslog.Facility; -import com.cloudbees.syslog.MessageFormat; -import com.cloudbees.syslog.Severity; -import com.cloudbees.syslog.sender.TcpSyslogMessageSender; - -... - -// Initialise sender -TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender(); -messageSender.setDefaultMessageHostname("myhostname"); // some syslog cloud services may use this field to transmit a secret key -messageSender.setDefaultAppName("myapp"); -messageSender.setDefaultFacility(Facility.USER); -messageSender.setDefaultSeverity(Severity.INFORMATIONAL); -messageSender.setSyslogServerHostname("127.0.0.1"); -messageSender.setSyslogServerPort(1234); -messageSender.setMessageFormat(MessageFormat.RFC_3164); // optional, default is RFC 3164 -messageSender.setSsl(true); - -// send a Syslog message -messageSender.sendMessage("This is a test message"); -``` - -## Sample TCP over SSL sender using RFC 5425 - -```java -import com.cloudbees.syslog.Facility; -import com.cloudbees.syslog.MessageFormat; -import com.cloudbees.syslog.Severity; -import com.cloudbees.syslog.sender.TcpSyslogMessageSender; - -... - -// Initialise sender -TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender(); -messageSender.setDefaultMessageHostname("myhostname"); // some syslog cloud services may use this field to transmit a secret key -messageSender.setDefaultAppName("myapp"); -messageSender.setDefaultFacility(Facility.USER); -messageSender.setDefaultSeverity(Severity.INFORMATIONAL); -messageSender.setSyslogServerHostname("127.0.0.1"); -// syslog-tls usually uses port 6514 as per https://tools.ietf.org/html/rfc5425#page-11 -messageSender.setSyslogServerPort(6514); -messageSender.setMessageFormat(MessageFormat.RFC_5425); -messageSender.setSsl(true); - -// send a Syslog message -messageSender.sendMessage("This is a test message"); -``` diff --git a/mvnw b/mvnw deleted file mode 100755 index 5643201..0000000 --- a/mvnw +++ /dev/null @@ -1,316 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you 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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /usr/local/etc/mavenrc ] ; then - . /usr/local/etc/mavenrc - fi - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`\\unset -f command; \\command -v java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - $MAVEN_DEBUG_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" \ - "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd deleted file mode 100644 index 23b7079..0000000 --- a/mvnw.cmd +++ /dev/null @@ -1,188 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* -if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - -FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% ^ - %JVM_CONFIG_MAVEN_PROPS% ^ - %MAVEN_OPTS% ^ - %MAVEN_DEBUG_OPTS% ^ - -classpath %WRAPPER_JAR% ^ - "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ - %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" -if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%"=="on" pause - -if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% - -cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index e27fb09..b4e31c0 100644 --- a/pom.xml +++ b/pom.xml @@ -1,316 +1,256 @@ +~ Copyright 2013, 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. +--> - 4.0.0 - - com.cloudbees - syslog-java-client - 1.1.8-SNAPSHOT - bundle - - syslog-java-client - Syslog Java Client - https://github.com/jenkinsci/syslog-java-client/ - 2014 - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - - Cyrille Le Clerc - cleclerc@cloudbees.com - - - - - scm:git:git://github.com/jenkinsci/syslog-java-client.git - scm:git:git@github.com:jenkinsci/syslog-java-client.git - HEAD - https://github.com/jenkinsci/syslog-java-client/ - - - - UTF-8 - UTF-8 - UTF-8 - - - - - com.github.spotbugs - spotbugs-annotations - 4.7.3 - true - - - com.google.code.findbugs - jsr305 - - - - - net.jcip - jcip-annotations - 1.0 - true - - - junit - junit - 4.13.2 - test - - - org.hamcrest - hamcrest - 2.2 - test - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.11.0 - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.5.0 - - - org.apache.maven.plugins - maven-source-plugin - 3.3.0 - - - org.apache.maven.plugins - maven-surefire-plugin - 3.1.2 - - - + 4.0.0 + com.teragrep + rlo_14 + ${revision}${sha1}${changelist} + jar + rlo_14 + Syslog Java Client + https://github.com/jenkinsci/syslog-java-client/ + 2014 + + UTF-8 + UTF-8 + UTF-8 + 0.0.1 + -SNAPSHOT + + 5.10.0-M1 + 1.36 + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + Cyrille Le Clerc + cleclerc@cloudbees.com + + + StrongestNumber9 + 9@teragrep.com + + + + scm:git:git://github.com/teragrep/rlo_14.git + scm:git:git@github.com:teragrep/rlo_14.git + https://github.com/teragrep/rlo_14/tree/master + + + + org.junit.jupiter + junit-jupiter-api + test + ${junit.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + test + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + test + + + + + + org.apache.rat + apache-rat-plugin + 0.15 + false + + + test + + check + + + + + false + + + Also allow the license url to be https. + + Licensed under the Apache License, Version 2.0 + + + + true + false + + + .git/** + .gitattributes + .gitignore + .gitmodules + + .github/workflows/*.yml + .github/workflows/*.yaml + toolchains.xml + settings.xml + rpm/rpm.pom.xml + + README.adoc + README.md + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 8 + 8 + + + + org.apache.maven.plugins + maven-deploy-plugin + 3.0.0 + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M7 + + all + false + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9.1 + + + attach-javadocs + + jar + + + 8 + + + + + + + + + publish-maven-central + - - com.github.spotbugs - spotbugs-maven-plugin - 4.7.3.4 + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + - High + + --pinentry-mode + loopback + - - - spotbugs - - check - - verify - - - - - org.apache.felix - maven-bundle-plugin - 5.1.9 - true - - - maven-enforcer-plugin - 3.3.0 - - - display-info - - display-info - enforce - - validate - - - - [3.8.1,) - 3.8.1 required to no longer download dependencies via HTTP (use HTTPS instead). - - - [1.8.0,] - - - - - org.apache.logging.log4j:*:(,2.15.0-rc1] - - - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - all,-missing,-reference - en_US - - - - org.apache.maven.plugins - maven-release-plugin - 3.0.1 - - false - jenkins-release - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.13 - true + + + + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + ossrh + Central Repository OSSRH + https://oss.sonatype.org/service/local/staging/deploy/maven2/ + + + + + publish-github-packages + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + sign-artifacts + verify + + sign + - sonatype-nexus-staging - https://oss.sonatype.org/ - true + + --pinentry-mode + loopback + - + + + - - - - jdk-8-and-below - - (,1.8] - - - - - maven-compiler-plugin - - 1.8 - 1.8 - 1.8 - 1.8 - - - - maven-javadoc-plugin - - 1.8 - - - - - - - jdk-9-and-above - - [9,) - - - - - maven-compiler-plugin - - 8 - 8 - - - - maven-javadoc-plugin - - 8 - - - - - - - jenkins-release - - - - org.apache.maven.plugins - maven-gpg-plugin - 3.1.0 - - - sign-artifacts - - sign - - verify - - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar-no-fork - - - - - - - - - network-constrained - - - env.CI - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - com.cloudbees.syslog.sender.TcpSyslogMessageSenderTest - - - - - - - + + + + github + GitHub Packages + https://maven.pkg.github.com/teragrep/rlo_14 + + + + diff --git a/src/main/java/com/cloudbees/syslog/MessageFormat.java b/src/main/java/com/cloudbees/syslog/MessageFormat.java deleted file mode 100644 index 23f336e..0000000 --- a/src/main/java/com/cloudbees/syslog/MessageFormat.java +++ /dev/null @@ -1,36 +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; - -/** - * Format of the Syslog message. - * - * @author Cyrille Le Clerc - */ -public enum MessageFormat { - /** - * RFC 3614 - BSD syslog Protocol - */ - RFC_3164, - /** - * RFC 5424 - The Syslog Protocol - */ - RFC_5424, - /** - * RFC 5425 - Transport Layer Security (TLS) Transport Mapping for Syslog - */ - RFC_5425 -} diff --git a/src/main/java/com/cloudbees/syslog/SyslogMessage.java b/src/main/java/com/cloudbees/syslog/SyslogMessage.java deleted file mode 100755 index 7af7d74..0000000 --- a/src/main/java/com/cloudbees/syslog/SyslogMessage.java +++ /dev/null @@ -1,450 +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; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; - -import java.io.CharArrayWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; - -import com.cloudbees.syslog.util.CachingReference; -import com.cloudbees.syslog.util.ConcurrentDateFormat; - -/** - * Syslog message as defined in RFC 5424 - The Syslog Protocol. - * - * Also compatible with RFC-3164: The BSD syslog Protocol, - * - * @author Cyrille Le Clerc - */ -public class SyslogMessage { - public final static char SP = ' '; - public final static char NILVALUE = '-'; - - private final static int DEFAULT_CONCURRENCY = 50; - protected final static ConcurrentDateFormat rfc3339DateFormat; - protected final static ConcurrentDateFormat rfc3164DateFormat; - private static CachingReference localhostNameReference = new CachingReference(10, TimeUnit.SECONDS) { - @Override - protected String newObject() { - try { - return InetAddress.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - return String.valueOf(NILVALUE); - } - } - }; - - static { - int concurrency; - try { - concurrency = Integer.parseInt(System.getProperty(SyslogMessage.class.getPackage().getName() + ".concurrency", String.valueOf(DEFAULT_CONCURRENCY))); - } catch (Exception e) { - concurrency = DEFAULT_CONCURRENCY; - } - - rfc3339DateFormat = new ConcurrentDateFormat( - "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", - Locale.US, - TimeZone.getTimeZone("GMT"), - concurrency); - - /* - * According to RFC31614- 4.1.2 HEADER Part of a syslog Packet, - * we should use local time and not GMT. - * - * The TIMESTAMP field is the local time and is in the format of "Mmm dd hh:mm:ss" (without the quote marks) - * - */ - rfc3164DateFormat = new ConcurrentDateFormat( - "MMM dd HH:mm:ss", - Locale.US, - TimeZone.getDefault(), - concurrency); - } - - private Facility facility; - private Severity severity; - private Long timestamp; - private String hostname; - private String appName; - private String procId; - private String msgId; - private Set sdElements; - /** - * 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 CharArrayWriter 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 Date getTimestamp() { - return timestamp == null ? null : new Date(timestamp); - } - - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp == null ? null : timestamp.getTime(); - } - - public SyslogMessage withTimestamp(long timestamp) { - this.timestamp = timestamp; - return this; - } - - public SyslogMessage withTimestamp(Date timestamp) { - this.timestamp = timestamp == null ? null : timestamp.getTime(); - 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 CharArrayWriter getMsg() { - return msg; - } - - public void setMsg(CharArrayWriter msg) { - this.msg = msg; - } - - public SyslogMessage withMsg(CharArrayWriter msg) { - this.msg = msg; - return this; - } - - public SyslogMessage withMsg(final String msg) { - return withMsg(new CharArrayWriter() { - { - append(msg); - } - }); - } - - public Set getSDElements() { - Set ssde = sdElements; - if (ssde == null) { - ssde = new HashSet<>(0); - } - return ssde; - } - - public void setSDElements(Set ssde) { - this.sdElements = ssde; - } - - public SyslogMessage withSDElement(SDElement sde) { - if (sdElements == null) { - sdElements = new HashSet<>(); - } - sdElements.add(sde); - return this; - } - - /** - * Generates a Syslog message complying to the RFC-5424 format - * or to the RFC-3164 format. - * - * @param messageFormat message format, not {@code null} - */ - public String toSyslogMessage(MessageFormat messageFormat) { - switch (messageFormat) { - case RFC_3164: - return toRfc3164SyslogMessage(); - case RFC_5424: - return toRfc5424SyslogMessage(); - case RFC_5425: - return toRfc5425SyslogMessage(); - default: - throw new IllegalStateException("Unsupported message format '" + messageFormat + "'"); - } - } - - /** - * Generates a Syslog message complying to the RFC-5424 format - * or to the RFC-3164 format. - * - * @param messageFormat message format - * @param out output {@linkplain Writer} - */ - public void toSyslogMessage(@NonNull MessageFormat messageFormat, @NonNull Writer out) throws IOException { - switch (messageFormat) { - case RFC_3164: - toRfc3164SyslogMessage(out); - break; - case RFC_5424: - toRfc5424SyslogMessage(out); - break; - case RFC_5425: - toRfc5425SyslogMessage(out); - break; - default: - throw new IllegalStateException("Unsupported message format '" + messageFormat + "'"); - } - } - - /** - * Generates an RFC-5425 message. - */ - public String toRfc5425SyslogMessage() { - - StringWriter sw = new StringWriter(msg == null ? 32 : msg.size() + 32); - try { - toRfc5425SyslogMessage(sw); - } catch (IOException e) { - throw new IllegalStateException(e); - } - return sw.toString(); - } - - /** - * Generates an RFC-5425 message. - */ - public void toRfc5425SyslogMessage(Writer out) throws IOException { - - String rfc5424Message = toRfc5424SyslogMessage(); - int length = rfc5424Message.getBytes(StandardCharsets.UTF_8).length; - out.write(String.valueOf(length)); - out.write(SP); - out.write(rfc5424Message); - } - - /** - * Generates an RFC-5424 message. - */ - public String toRfc5424SyslogMessage() { - - StringWriter sw = new StringWriter(msg == null ? 32 : msg.size() + 32); - 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(Writer out) throws IOException { - - int pri = facility.numericalCode() * 8 + severity.numericalCode(); - - out.write('<'); - out.write(String.valueOf(pri)); - out.write('>'); - out.write('1'); // version - out.write(SP); - out.write(rfc3339DateFormat.format(timestamp == null ? new Date() : new Date(timestamp))); // message time - out.write(SP); - out.write(hostname == null ? localhostNameReference.get() : hostname); // emitting server hostname - out.write(SP); - writeNillableValue(appName, out); // appname - out.write(SP); - writeNillableValue(procId, out); // PID - out.write(SP); - writeNillableValue(msgId, out);// Message ID - out.write(SP); - writeStructuredDataOrNillableValue(sdElements, out); - if (msg != null) { - out.write(SP); - msg.writeTo(out); - } - } - - /** - * Generates an RFC-3164 message. - * - * @see #toRfc3164SyslogMessage(java.io.Writer) - */ - public String toRfc3164SyslogMessage() { - - StringWriter sw = new StringWriter(msg == null ? 32 : msg.size() + 32); - try { - toRfc3164SyslogMessage(sw); - } catch (IOException e) { - throw new IllegalStateException(e); - } - return sw.toString(); - } - - /** - * Generates an RFC-3164 message. - */ - public void toRfc3164SyslogMessage(Writer out) throws IOException { - - int pri = facility.numericalCode() * 8 + severity.numericalCode(); - - out.write('<'); - out.write(Integer.toString(pri)); - out.write('>'); - out.write(rfc3164DateFormat.format(timestamp == null ? new Date() : new Date(timestamp))); // message time - out.write(SP); - out.write(hostname == null ? localhostNameReference.get() : hostname); // emitting server hostname - out.write(SP); - writeNillableValue(appName, out); // appname - - if (msg != null) { - out.write(": "); - msg.writeTo(out); - } - } - - protected void writeNillableValue(@Nullable String value, @NonNull Writer out) throws IOException { - if (value == null) { - out.write(NILVALUE); - } else { - out.write(value); - } - } - - protected void writeStructuredDataOrNillableValue(@Nullable Set ssde, @NonNull Writer out) throws IOException { - if (ssde == null || ssde.isEmpty()) { - out.write(NILVALUE); - } else { - for (SDElement sde : ssde) { - writeSDElement(sde, out); - } - } - } - - protected void writeSDElement(@NonNull SDElement sde, @NonNull Writer out) throws IOException { - out.write("["); - out.write(sde.getSdID()); - for (SDParam sdp : sde.getSdParams()) { - writeSDParam(sdp, out); - } - out.write("]"); - } - - protected void writeSDParam(@NonNull SDParam sdp, @NonNull Writer out) throws IOException { - out.write(SP); - out.write(sdp.getParamName()); - out.write('='); - out.write('"'); - out.write(getEscapedParamValue(sdp.getParamValue())); - out.write('"'); - } - - 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/main/java/com/cloudbees/syslog/integration/jul/AbstractHandler.java b/src/main/java/com/cloudbees/syslog/integration/jul/AbstractHandler.java deleted file mode 100644 index d51c6ee..0000000 --- a/src/main/java/com/cloudbees/syslog/integration/jul/AbstractHandler.java +++ /dev/null @@ -1,118 +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.integration.jul.util.LogManagerHelper; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.logging.Filter; -import java.util.logging.Formatter; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; -import java.util.logging.SimpleFormatter; - -/** - * @author Cyrille Le Clerc - */ -public abstract class AbstractHandler extends Handler { - - private Level logLevel = Level.ALL; - private Filter filter; - private Formatter formatter; - - public AbstractHandler() { - super(); - LogManager manager = LogManager.getLogManager(); - String cname = getClass().getName(); - this.logLevel = LogManagerHelper.getLevelProperty(manager, cname + ".level", Level.INFO); - this.filter = LogManagerHelper.getFilterProperty(manager, cname + ".filter", null); - this.formatter = LogManagerHelper.getFormatterProperty(manager, cname + ".formatter", getDefaultFormatter()); - } - - - public AbstractHandler(@NonNull Level level, @Nullable Filter filter) { - this.logLevel = level; - this.filter = filter; - this.formatter = getDefaultFormatter(); - } - - - /** - * For extensibility - * - * @return - */ - @NonNull - protected Formatter getDefaultFormatter() { - return new SimpleFormatter(); - } - - - /** - * {@inheritDoc} - */ - @Override - public boolean isLoggable(LogRecord record) { - if (record == null) { - return false; - } - return super.isLoggable(record); - } - - /** - * {@inheritDoc} - */ - @Override - public Level getLevel() { - return this.logLevel; - } - - /** - * {@inheritDoc} - */ - @Nullable - @Override - public Filter getFilter() { - return filter; - } - - /** - * {@inheritDoc} - */ - @Override - public Formatter getFormatter() { - return formatter; - } - - /** - * {@inheritDoc} - */ - @Override - public void setFormatter(Formatter formatter) throws SecurityException { - this.formatter = formatter; - } -} diff --git a/src/main/java/com/cloudbees/syslog/integration/jul/SyslogHandler.java b/src/main/java/com/cloudbees/syslog/integration/jul/SyslogHandler.java deleted file mode 100644 index ea082b6..0000000 --- a/src/main/java/com/cloudbees/syslog/integration/jul/SyslogHandler.java +++ /dev/null @@ -1,176 +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.Facility; -import com.cloudbees.syslog.Severity; -import com.cloudbees.syslog.SyslogMessage; -import com.cloudbees.syslog.integration.jul.util.LevelHelper; -import com.cloudbees.syslog.integration.jul.util.LogManagerHelper; -import com.cloudbees.syslog.sender.SyslogMessageSender; -import com.cloudbees.syslog.sender.UdpSyslogMessageSender; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.io.IOException; -import java.util.logging.Filter; -import java.util.logging.Formatter; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.LogRecord; - -/** - * @author Cyrille Le Clerc - */ -public class SyslogHandler extends AbstractHandler { - - private SyslogMessageSender syslogMessageSender; - - private String appName; - private Facility facility = Facility.USER; - private Severity severity = Severity.DEBUG; - private String messageHostname; - - public SyslogHandler() { - super(); - LogManager manager = LogManager.getLogManager(); - - String cname = getClass().getName(); - - UdpSyslogMessageSender udpSender = new UdpSyslogMessageSender(); - udpSender.setSyslogServerHostname(LogManagerHelper.getStringProperty(manager, cname + ".syslogServerHostname", SyslogMessageSender.DEFAULT_SYSLOG_HOST)); - udpSender.setSyslogServerPort(LogManagerHelper.getIntProperty(manager, cname + ".syslogServerPort", SyslogMessageSender.DEFAULT_SYSLOG_PORT)); - - appName = LogManagerHelper.getStringProperty(manager, cname + ".appName", this.appName); - udpSender.setDefaultAppName(appName); - facility = Facility.fromLabel(LogManagerHelper.getStringProperty(manager, cname + ".facility", this.facility.label())); - udpSender.setDefaultFacility(facility); - severity = Severity.fromLabel(LogManagerHelper.getStringProperty(manager, cname + ".severity", this.severity.label())); - udpSender.setDefaultSeverity(severity); - messageHostname = LogManagerHelper.getStringProperty(manager, cname + ".messageHostname", this.messageHostname); - udpSender.setDefaultMessageHostname(messageHostname); - - this.syslogMessageSender = udpSender; - } - - public SyslogHandler(@NonNull SyslogMessageSender syslogMessageSender) { - this(syslogMessageSender, Level.INFO, null); - } - - public SyslogHandler(@NonNull SyslogMessageSender syslogMessageSender, @NonNull Level level, @Nullable Filter filter) { - super(level, filter); - this.syslogMessageSender = syslogMessageSender; - } - - @NonNull - @Override - protected Formatter getDefaultFormatter() { - return new SyslogMessageFormatter(); - } - - @Override - public void publish(LogRecord record) { - if (!isLoggable(record)) - return; - - String msg = getFormatter().format(record); - - Severity severity = LevelHelper.toSeverity(record.getLevel()); - if (severity == null) - severity = this.severity; - - SyslogMessage message = new SyslogMessage() - .withTimestamp(record.getMillis()) - .withSeverity(severity) - .withAppName(this.appName) - .withHostname(this.messageHostname) - .withFacility(this.facility) - .withMsg(msg); - - try { - syslogMessageSender.sendMessage(message); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void flush() { - - } - - @Override - public void close() throws SecurityException { - try { - syslogMessageSender.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public String getEncoding() { - throw new IllegalStateException(); - } - - public String getAppName() { - return appName; - } - - public void setAppName(String appName) { - this.appName = appName; - } - - public Facility getFacility() { - return facility; - } - - public void setFacility(Facility facility) { - this.facility = facility; - } - - public Severity getSeverity() { - return severity; - } - - public void setSeverity(Severity severity) { - this.severity = severity; - } - - public String getMessageHostname() { - return messageHostname; - } - - public void setMessageHostname(String messageHostname) { - this.messageHostname = messageHostname; - } - - public SyslogMessageSender getSyslogMessageSender() { - return syslogMessageSender; - } - - public void setSyslogMessageSender(SyslogMessageSender syslogMessageSender) { - this.syslogMessageSender = syslogMessageSender; - } -} diff --git a/src/main/java/com/cloudbees/syslog/integration/jul/SyslogMessageFormatter.java b/src/main/java/com/cloudbees/syslog/integration/jul/SyslogMessageFormatter.java deleted file mode 100644 index cfc3c6b..0000000 --- a/src/main/java/com/cloudbees/syslog/integration/jul/SyslogMessageFormatter.java +++ /dev/null @@ -1,50 +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 java.io.PrintWriter; -import java.io.StringWriter; -import java.util.logging.Formatter; -import java.util.logging.LogRecord; - -/** - * @author Cyrille Le Clerc - */ -public class SyslogMessageFormatter extends Formatter { - - @Override - public String format(LogRecord record) { - String message = formatMessage(record); - String throwable = ""; - if (record.getThrown() != null) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - pw.println(); - record.getThrown().printStackTrace(pw); - pw.close(); - throwable = sw.toString(); - } - return record.getLevel() + " [" + Thread.currentThread().getName() + "] " + record.getLoggerName() + ": " + message + throwable; - } -} diff --git a/src/main/java/com/cloudbees/syslog/integration/jul/util/LevelHelper.java b/src/main/java/com/cloudbees/syslog/integration/jul/util/LevelHelper.java deleted file mode 100644 index 6c8787b..0000000 --- a/src/main/java/com/cloudbees/syslog/integration/jul/util/LevelHelper.java +++ /dev/null @@ -1,97 +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.util; - -import com.cloudbees.syslog.Severity; - -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; - -/** - * @author Cyrille Le Clerc - */ -public class LevelHelper { - - public final static List levels = Collections.unmodifiableList(Arrays.asList(Level.OFF, Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG, - Level.FINE, Level.FINER, Level.FINEST, Level.ALL)); - - public final static Map levelsByName; - public final static Map levelsByValue; - private final static Map julLevelToSyslogSeverity; - - static { - Map levelsByNameMap = new HashMap<>(); - Map levelsByValueMap = new HashMap<>(); - for (Level level : levels) { - levelsByNameMap.put(level.getName(), level); - levelsByValueMap.put(level.intValue(), level); - } - levelsByName = Collections.unmodifiableMap(levelsByNameMap); - levelsByValue = Collections.unmodifiableMap(levelsByValueMap); - - julLevelToSyslogSeverity = Collections.unmodifiableMap(new HashMap() { - { - put(Level.CONFIG, Severity.INFORMATIONAL); - put(Level.FINE, Severity.DEBUG); - put(Level.FINER, Severity.DEBUG); - put(Level.FINEST, Severity.DEBUG); - put(Level.INFO, Severity.INFORMATIONAL); - put(Level.SEVERE, Severity.ERROR); - put(Level.WARNING, Severity.WARNING); - } - }); - } - - /** - * Simplification: use delegate to {@link Level#parse(String)} even if the behavior is slightly different for localized log levels. - * - * @param name {@code null} or empty returns {@code null} - * @return - */ - @Nullable - public static Level findLevel(@Nullable String name) { - if(name == null || name.isEmpty()) - return null; - return Level.parse(name); - - } - - @Nullable - public static Severity toSeverity(@Nullable Level level) { - return julLevelToSyslogSeverity.get(level); - } - - /** - * Compare on {@link java.util.logging.Level#intValue()} - */ - public static Comparator comparator() { - return Comparator.comparingInt(Level::intValue); - } -} diff --git a/src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java b/src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java deleted file mode 100644 index 3a4f456..0000000 --- a/src/main/java/com/cloudbees/syslog/integration/jul/util/LogManagerHelper.java +++ /dev/null @@ -1,177 +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.util; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import java.util.logging.Filter; -import java.util.logging.Formatter; -import java.util.logging.Level; -import java.util.logging.LogManager; - -/** - * @author Cyrille Le Clerc - */ -public class LogManagerHelper { - - /** - * Visible version of {@link java.util.logging.LogManager#getLevelProperty(String, java.util.logging.Level)}. - * - * If the property is not defined or cannot be parsed we return the given default value. - */ - @Nullable - public static Level getLevelProperty(@NonNull LogManager manager, @NonNull String name, @Nullable Level defaultValue) { - if (name == null) { - return defaultValue; - } - String val = manager.getProperty(name); - if (val == null) { - return defaultValue; - } - Level l = LevelHelper.findLevel(val.trim()); - return l != null ? l : defaultValue; - } - - - /** - * Visible version of {@link java.util.logging.LogManager#getFilterProperty(String, java.util.logging.Filter)}. - * - * We return an instance of the class named by the "name" property. - * - * If the property is not defined or has problems we return the defaultValue. - */ - @Nullable - public static Filter getFilterProperty(@NonNull LogManager manager, @Nullable String name, @Nullable Filter defaultValue) { - if (name == null) { - return defaultValue; - } - String val = manager.getProperty(name); - try { - if (val != null) { - Class clz = ClassLoader.getSystemClassLoader().loadClass(val); - return (Filter) clz.newInstance(); - } - } catch (Exception ex) { - // We got one of a variety of exceptions in creating the - // class or creating an instance. - // Drop through. - } - // We got an exception. Return the defaultValue. - return defaultValue; - } - - - /** - * Visible version of {@link java.util.logging.LogManager#getFormatterProperty(String, java.util.logging.Formatter)} . - * - * We return an instance of the class named by the "name" property. - * - * If the property is not defined or has problems we return the defaultValue. - */ - public static Formatter getFormatterProperty(@NonNull LogManager manager, @Nullable String name, @Nullable Formatter defaultValue) { - if (name == null) { - return defaultValue; - } - String val = manager.getProperty(name); - try { - if (val != null) { - Class clz = ClassLoader.getSystemClassLoader().loadClass(val); - return (Formatter) clz.newInstance(); - } - } catch (Exception ex) { - // We got one of a variety of exceptions in creating the - // class or creating an instance. - // Drop through. - } - // We got an exception. Return the defaultValue. - return defaultValue; - } - - - /** - * Visible version of {@link java.util.logging.LogManager#getStringProperty(String, String)}. - * - * If the property is not defined we return the given default value. - */ - public static String getStringProperty(@NonNull LogManager manager, @Nullable String name, String defaultValue) { - if (name == null) { - return defaultValue; - } - String val = manager.getProperty(name); - if (val == null) { - return defaultValue; - } - return val.trim(); - } - - - /** - * Visible version of {@link java.util.logging.LogManager#getIntProperty(String, int)}. - * - * Method to get an integer property. - * - * If the property is not defined or cannot be parsed we return the given default value. - */ - public static int getIntProperty(@NonNull LogManager manager, @Nullable String name, int defaultValue) { - if (name == null) { - return defaultValue; - } - String val = manager.getProperty(name); - if (val == null) { - return defaultValue; - } - try { - return Integer.parseInt(val.trim()); - } catch (Exception ex) { - return defaultValue; - } - } - - - /** - * Visible version of {@link java.util.logging.LogManager#getIntProperty(String, int)}. - * - * Method to get a boolean property. - * - * If the property is not defined or cannot be parsed we return the given default value. - */ - public static boolean getBooleanProperty(@NonNull LogManager manager, @Nullable String name, boolean defaultValue) { - if (name == null) { - return defaultValue; - } - String val = manager.getProperty(name); - if (val == null) { - return defaultValue; - } - val = val.toLowerCase(); - if (val.equals("true") || val.equals("1")) { - return true; - } else if (val.equals("false") || val.equals("0")) { - return false; - } - return defaultValue; - } - - -} diff --git a/src/main/java/com/cloudbees/syslog/sender/AbstractSyslogMessageSender.java b/src/main/java/com/cloudbees/syslog/sender/AbstractSyslogMessageSender.java deleted file mode 100644 index e5d3d62..0000000 --- a/src/main/java/com/cloudbees/syslog/sender/AbstractSyslogMessageSender.java +++ /dev/null @@ -1,175 +0,0 @@ -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 com.cloudbees.syslog.util.InternalLogger; - -import edu.umd.cs.findbugs.annotations.NonNull; -import java.io.CharArrayWriter; -import java.io.IOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author Cyrille Le Clerc - */ -public abstract class AbstractSyslogMessageSender implements SyslogMessageSender { - /** - * @deprecated use {@link StandardCharsets#UTF_8} - */ - @Deprecated - protected final static Charset UTF_8 = StandardCharsets.UTF_8; - protected final InternalLogger logger = InternalLogger.getLogger(getClass()); - // default values - protected String defaultAppName; - protected Facility defaultFacility = Facility.USER; - protected String defaultMessageHostname; - protected Severity defaultSeverity = Severity.INFORMATIONAL; - // remote syslog server config - /** - * Format of messages accepted by the remote syslog server - * ({@link com.cloudbees.syslog.MessageFormat#RFC_3164 RFC_3164} or - * {@link com.cloudbees.syslog.MessageFormat#RFC_5424 RFC_5424}) - */ - protected MessageFormat messageFormat = DEFAULT_SYSLOG_MESSAGE_FORMAT; - // statistics - protected final AtomicInteger sendCounter = new AtomicInteger(); - protected final AtomicLong sendDurationInNanosCounter = new AtomicLong(); - protected final AtomicInteger sendErrorCounter = new AtomicInteger(); - - /** - * Send the given text message - * - * @param message - * @throws java.io.IOException - */ - @Override - public void sendMessage(CharArrayWriter message) throws IOException { - - SyslogMessage syslogMessage = new SyslogMessage() - .withAppName(defaultAppName) - .withFacility(defaultFacility) - .withHostname(defaultMessageHostname) - .withSeverity(defaultSeverity) - .withMsg(message); - - sendMessage(syslogMessage); - } - - @Override - public void sendMessage(CharSequence message) throws IOException { - CharArrayWriter writer = new CharArrayWriter(); - writer.append(message); - sendMessage(writer); - } - - /** - * Send the given {@link com.cloudbees.syslog.SyslogMessage}. - * - * @param message the message to send - * @throws IOException - */ - public abstract void sendMessage(@NonNull SyslogMessage message) throws IOException; - - public String getDefaultAppName() { - return defaultAppName; - } - - public Facility getDefaultFacility() { - return defaultFacility; - } - - public MessageFormat getMessageFormat() { - return messageFormat; - } - - public String getDefaultMessageHostname() { - return defaultMessageHostname; - } - - public int getSendCount() { - return sendCounter.get(); - } - - /** - * Human readable view of {@link #getSendDurationInNanos()} - * - * @return total duration spent sending syslog messages - */ - public long getSendDurationInMillis() { - return TimeUnit.MILLISECONDS.convert(getSendDurationInNanos(), TimeUnit.NANOSECONDS); - } - - /** - * Human readable view of {@link #getSendDurationInNanos()} - * - * @return total duration spent sending syslog messages - */ - public long getSendDurationInNanos() { - return sendDurationInNanosCounter.get(); - } - - public int getSendErrorCount() { - return sendErrorCounter.get(); - } - - public Severity getDefaultSeverity() { - return defaultSeverity; - } - - public void setDefaultAppName(String defaultAppName) { - this.defaultAppName = defaultAppName; - } - - public void setDefaultMessageHostname(String defaultHostname) { - this.defaultMessageHostname = defaultHostname; - } - - public void setDefaultFacility(Facility defaultFacility) { - this.defaultFacility = defaultFacility; - } - - public void setMessageFormat(MessageFormat messageFormat) { - this.messageFormat = messageFormat; - } - - public void setDefaultSeverity(Severity defaultSeverity) { - this.defaultSeverity = defaultSeverity; - } - - /** - * Set the hostname or IP of the syslog server to which messages will be - * sent. - * - * @param syslogServerHostname - * The hostname or IP address of the syslog server. - */ - public abstract void setSyslogServerHostname(final String syslogServerHostname); - - /** - * Set the port number of the syslog server to which messages will be sent. - * - * @param syslogServerPort - * The port to which syslog messages will be sent. - */ - public abstract void setSyslogServerPort(int syslogServerPort); - - @Override - public String toString() { - return getClass().getName() + "{" + - "defaultAppName='" + defaultAppName + '\'' + - ", defaultFacility=" + defaultFacility + - ", defaultMessageHostname='" + defaultMessageHostname + '\'' + - ", defaultSeverity=" + defaultSeverity + - ", messageFormat=" + messageFormat + - ", sendCounter=" + sendCounter + - ", sendDurationInNanosCounter=" + sendDurationInNanosCounter + - ", sendErrorCounter=" + sendErrorCounter + - '}'; - } -} diff --git a/src/main/java/com/cloudbees/syslog/sender/SyslogMessageSender.java b/src/main/java/com/cloudbees/syslog/sender/SyslogMessageSender.java deleted file mode 100644 index d9115b8..0000000 --- a/src/main/java/com/cloudbees/syslog/sender/SyslogMessageSender.java +++ /dev/null @@ -1,69 +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.SyslogMessage; -import com.cloudbees.syslog.MessageFormat; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import net.jcip.annotations.ThreadSafe; -import java.io.CharArrayWriter; -import java.io.Closeable; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -/** - * Send messages to a Syslog server. - * - * Implementation MUST be thread safe. - * - * @author Cyrille Le Clerc - */ -@ThreadSafe -public interface SyslogMessageSender extends Closeable { - long DEFAULT_INET_ADDRESS_TTL_IN_MILLIS = TimeUnit.MILLISECONDS.convert(30, TimeUnit.SECONDS); - long DEFAULT_INET_ADDRESS_TTL_IN_NANOS = TimeUnit.NANOSECONDS.convert(DEFAULT_INET_ADDRESS_TTL_IN_MILLIS, TimeUnit.MILLISECONDS); - String DEFAULT_SYSLOG_HOST = "localhost"; - MessageFormat DEFAULT_SYSLOG_MESSAGE_FORMAT = MessageFormat.RFC_3164; - int DEFAULT_SYSLOG_PORT = 514; - - /** - * Send the given message ; the Syslog fields (appName, severity, priority, hostname ...) are the default values - * of the {@linkplain com.cloudbees.syslog.sender.SyslogMessageSender MessageSender}. - * - * @param message the message to send - * @throws IOException - */ - void sendMessage(CharArrayWriter message) throws IOException; - - /** - * Send the given message ; the Syslog fields (appName, severity, priority, hostname ...) are the default values - * of the {@linkplain com.cloudbees.syslog.sender.SyslogMessageSender MessageSender}. - * - * @param message the message to send - * @throws IOException - */ - void sendMessage(@Nullable CharSequence message) throws IOException; - - /** - * Send the given {@link com.cloudbees.syslog.SyslogMessage}. - * - * @param message the message to send - * @throws IOException - */ - void sendMessage(@NonNull SyslogMessage message) throws IOException; -} diff --git a/src/main/java/com/cloudbees/syslog/sender/TcpSyslogMessageSender.java b/src/main/java/com/cloudbees/syslog/sender/TcpSyslogMessageSender.java deleted file mode 100644 index 249556f..0000000 --- a/src/main/java/com/cloudbees/syslog/sender/TcpSyslogMessageSender.java +++ /dev/null @@ -1,293 +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.SyslogMessage; -import com.cloudbees.syslog.util.CachingReference; -import com.cloudbees.syslog.util.IoUtils; - -import edu.umd.cs.findbugs.annotations.NonNull; -import edu.umd.cs.findbugs.annotations.Nullable; -import net.jcip.annotations.ThreadSafe; -import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import java.io.BufferedWriter; -import java.io.Closeable; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.math.BigInteger; -import java.net.ConnectException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; - -/** - * See RFC 6587 - Transmission of Syslog Messages over TCP - * - * @author Cyrille Le Clerc - */ -@ThreadSafe -public class TcpSyslogMessageSender extends AbstractSyslogMessageSender implements Closeable { - public final static int SETTING_SOCKET_CONNECT_TIMEOUT_IN_MILLIS_DEFAULT_VALUE = 500; - public final static int SETTING_MAX_RETRY = 2; - - /** - * {@link java.net.InetAddress InetAddress} of the remote Syslog Server. - * - * The {@code InetAddress} is refreshed regularly to handle DNS changes (default {@link #DEFAULT_INET_ADDRESS_TTL_IN_MILLIS}) - * - * Default value: {@link #DEFAULT_SYSLOG_HOST} - */ - protected CachingReference syslogServerHostnameReference; - /** - * Listen port of the remote Syslog server. - * - * Default: {@link #DEFAULT_SYSLOG_PORT} - */ - protected int syslogServerPort = DEFAULT_SYSLOG_PORT; - - private Socket socket; - private Writer writer; - private int socketConnectTimeoutInMillis = SETTING_SOCKET_CONNECT_TIMEOUT_IN_MILLIS_DEFAULT_VALUE; - private boolean ssl; - private SSLContext sslContext; - /** - * Number of retries to send a message before throwing an exception. - */ - private int maxRetryCount = SETTING_MAX_RETRY; - /** - * Number of exceptions trying to send message. - */ - protected final AtomicInteger trySendErrorCounter = new AtomicInteger(); - - // use the CR LF non transparent framing as described in "3.4.2. Non-Transparent-Framing" - private String postfix = "\r\n"; - - @Override - public synchronized void sendMessage(@NonNull SyslogMessage message) throws IOException { - sendCounter.incrementAndGet(); - long nanosBefore = System.nanoTime(); - - try { - Exception lastException = null; - for (int i = 0; i <= maxRetryCount; i++) { - try { - if (logger.isLoggable(Level.FINEST)) { - logger.finest("Send syslog message " + message.toSyslogMessage(messageFormat)); - } - ensureSyslogServerConnection(); - message.toSyslogMessage(messageFormat, writer); - writer.write(postfix); - writer.flush(); - return; - } catch (IOException | RuntimeException e) { - lastException = e; - IoUtils.closeQuietly(socket, writer); - trySendErrorCounter.incrementAndGet(); - } - } - if (lastException != null) { - sendErrorCounter.incrementAndGet(); - if (lastException instanceof IOException) { - throw (IOException) lastException; - } else if (lastException instanceof RuntimeException) { - throw (RuntimeException) lastException; - } - } - } finally { - sendDurationInNanosCounter.addAndGet(System.nanoTime() - nanosBefore); - } - } - - private synchronized void ensureSyslogServerConnection() throws IOException { - InetAddress inetAddress = syslogServerHostnameReference.get(); - if (socket != null && !Objects.equals(socket.getInetAddress(), inetAddress)) { - logger.info("InetAddress of the Syslog Server have changed, create a new connection. " + - "Before=" + socket.getInetAddress() + ", new=" + inetAddress); - IoUtils.closeQuietly(socket, writer); - writer = null; - socket = null; - } - boolean socketIsValid; - try { - socketIsValid = socket != null && - socket.isConnected() - && socket.isBound() - && !socket.isClosed() - && !socket.isInputShutdown() - && !socket.isOutputShutdown(); - } catch (Exception e) { - socketIsValid = false; - } - if (!socketIsValid) { - writer = null; - try { - if (ssl) { - if (sslContext == null) { - socket = SSLSocketFactory.getDefault().createSocket(); - } else { - socket = sslContext.getSocketFactory().createSocket(); - } - } else { - socket = SocketFactory.getDefault().createSocket(); - } - socket.setKeepAlive(true); - socket.connect( - new InetSocketAddress(inetAddress, syslogServerPort), - socketConnectTimeoutInMillis); - - if (socket instanceof SSLSocket && logger.isLoggable(Level.FINER)) { - try { - SSLSocket sslSocket = (SSLSocket) socket; - SSLSession session = sslSocket.getSession(); - logger.finer("The Certificates used by peer"); - for (Certificate certificate : session.getPeerCertificates()) { - if (certificate instanceof X509Certificate) { - X509Certificate x509Certificate = (X509Certificate) certificate; - logger.finer("" + x509Certificate.getSubjectDN()); - } else { - logger.finer("" + certificate); - } - } - logger.finer("Peer host is " + session.getPeerHost()); - logger.finer("Cipher is " + session.getCipherSuite()); - logger.finer("Protocol is " + session.getProtocol()); - logger.finer("ID is " + new BigInteger(session.getId())); - logger.finer("Session created in " + session.getCreationTime()); - logger.finer("Session accessed in " + session.getLastAccessedTime()); - } catch (Exception e) { - logger.warn("Exception dumping debug info for " + socket, e); - } - } - } catch (IOException e) { - ConnectException ce = new ConnectException("Exception connecting to " + inetAddress + ":" + syslogServerPort); - ce.initCause(e); - throw ce; - } - } - if (writer == null) { - writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)); - } - } - - @Override - public void setSyslogServerHostname(final String syslogServerHostname) { - this.syslogServerHostnameReference = new CachingReference(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() { - if (syslogServerHostnameReference == null) - return null; - InetAddress inetAddress = syslogServerHostnameReference.get(); - return inetAddress == null ? null : inetAddress.getHostName(); - } - - public int getSyslogServerPort() { - return syslogServerPort; - } - - public boolean isSsl() { - return ssl; - } - - public void setSsl(boolean ssl) { - this.ssl = ssl; - } - - public synchronized void setSSLContext(SSLContext sslContext) { - this.sslContext = sslContext; - } - - public synchronized SSLContext getSSLContext() { - return this.sslContext; - } - - public int getSocketConnectTimeoutInMillis() { - return socketConnectTimeoutInMillis; - } - - public int getMaxRetryCount() { - return maxRetryCount; - } - - public int getTrySendErrorCounter() { - return trySendErrorCounter.get(); - } - - public void setSocketConnectTimeoutInMillis(int socketConnectTimeoutInMillis) { - this.socketConnectTimeoutInMillis = socketConnectTimeoutInMillis; - } - - public void setMaxRetryCount(int maxRetryCount) { - this.maxRetryCount = maxRetryCount; - } - - public synchronized void setPostfix(String postfix) { - this.postfix = postfix; - } - - @Override - public String toString() { - return getClass().getName() + "{" + - "syslogServerHostname='" + this.getSyslogServerHostname() + '\'' + - ", syslogServerPort='" + this.getSyslogServerPort() + '\'' + - ", ssl=" + ssl + - ", maxRetryCount=" + maxRetryCount + - ", socketConnectTimeoutInMillis=" + socketConnectTimeoutInMillis + - ", defaultAppName='" + defaultAppName + '\'' + - ", defaultFacility=" + defaultFacility + - ", defaultMessageHostname='" + defaultMessageHostname + '\'' + - ", defaultSeverity=" + defaultSeverity + - ", messageFormat=" + messageFormat + - ", sendCounter=" + sendCounter + - ", sendDurationInNanosCounter=" + sendDurationInNanosCounter + - ", sendErrorCounter=" + sendErrorCounter + - ", trySendErrorCounter=" + trySendErrorCounter + - '}'; - } - - @Override - public void close() throws IOException { - this.socket.close(); - } -} diff --git a/src/main/java/com/cloudbees/syslog/sender/UdpSyslogMessageSender.java b/src/main/java/com/cloudbees/syslog/sender/UdpSyslogMessageSender.java deleted file mode 100644 index a0399e3..0000000 --- a/src/main/java/com/cloudbees/syslog/sender/UdpSyslogMessageSender.java +++ /dev/null @@ -1,154 +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.SyslogMessage; -import com.cloudbees.syslog.util.CachingReference; - -import edu.umd.cs.findbugs.annotations.Nullable; -import net.jcip.annotations.ThreadSafe; -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.util.logging.Level; - -/** - * Syslog message sender over UDP. - * - * TODO optimize performances recycling the byte arrays. Note: {@link java.io.ByteArrayOutputStream} - * can be subclassed to access to the underlying {@code byte[]}. - * - * @author Cyrille Le Clerc - */ -@ThreadSafe -public class UdpSyslogMessageSender extends AbstractSyslogMessageSender implements Closeable { - /** - * {@link java.net.InetAddress InetAddress} of the remote Syslog Server. - * - * The {@code InetAddress} is refreshed regularly to handle DNS changes (default {@link #DEFAULT_INET_ADDRESS_TTL_IN_MILLIS}) - * - * Default value: {@link #DEFAULT_SYSLOG_HOST} - */ - protected CachingReference syslogServerHostnameReference; - /** - * Listen port of the remote Syslog server. - * - * Default: {@link #DEFAULT_SYSLOG_PORT} - */ - protected int syslogServerPort = DEFAULT_SYSLOG_PORT; - - private DatagramSocket datagramSocket; - - public UdpSyslogMessageSender() { - try { - setSyslogServerHostname(DEFAULT_SYSLOG_HOST); - datagramSocket = new DatagramSocket(); - } catch (IOException e) { - throw new IllegalStateException("Exception initializing datagramSocket", e); - } - } - - /** - * Send the given {@link com.cloudbees.syslog.SyslogMessage} over UDP. - * - * @param message the message to send - * @throws IOException - */ - @Override - public void sendMessage(SyslogMessage message) throws IOException { - sendCounter.incrementAndGet(); - long nanosBefore = System.nanoTime(); - - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Writer out = new OutputStreamWriter(baos, StandardCharsets.UTF_8); - message.toSyslogMessage(messageFormat, out); - out.flush(); - - if (logger.isLoggable(Level.FINEST)) { - logger.finest("Send syslog message " + new String(baos.toByteArray(), StandardCharsets.UTF_8)); - } - byte[] bytes = baos.toByteArray(); - - DatagramPacket packet = new DatagramPacket(bytes, bytes.length, syslogServerHostnameReference.get(), syslogServerPort); - datagramSocket.send(packet); - } catch (IOException | RuntimeException e) { - sendErrorCounter.incrementAndGet(); - throw e; - } finally { - sendDurationInNanosCounter.addAndGet(System.nanoTime() - nanosBefore); - } - } - - - @Override - public void setSyslogServerHostname(final String syslogServerHostname) { - this.syslogServerHostnameReference = new CachingReference(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