(DEFAULT_INET_ADDRESS_TTL_IN_NANOS) {
107 | @Nullable
108 | @Override
109 | protected InetAddress newObject() {
110 | try {
111 | return InetAddress.getByName(syslogServerHostname);
112 | } catch (UnknownHostException e) {
113 | throw new IllegalStateException(e);
114 | }
115 | }
116 | };
117 | }
118 |
119 | @Override
120 | public void setSyslogServerPort(int syslogServerPort) {
121 | this.syslogServerPort = syslogServerPort;
122 | }
123 |
124 | @Nullable
125 | public String getSyslogServerHostname() {
126 | InetAddress inetAddress = syslogServerHostnameReference.get();
127 | return inetAddress == null ? null : inetAddress.getHostName();
128 | }
129 |
130 | public int getSyslogServerPort() {
131 | return syslogServerPort;
132 | }
133 |
134 | @Override
135 | public String toString() {
136 | return getClass().getName() + "{" +
137 | "syslogServerHostname='" + this.getSyslogServerHostname() + '\'' +
138 | ", syslogServerPort='" + this.getSyslogServerPort() + '\'' +
139 | ", defaultAppName='" + defaultAppName + '\'' +
140 | ", defaultFacility=" + defaultFacility +
141 | ", defaultMessageHostname='" + defaultMessageHostname + '\'' +
142 | ", defaultSeverity=" + defaultSeverity +
143 | ", messageFormat=" + messageFormat +
144 | ", sendCounter=" + sendCounter +
145 | ", sendDurationInNanosCounter=" + sendDurationInNanosCounter +
146 | ", sendErrorCounter=" + sendErrorCounter +
147 | '}';
148 | }
149 |
150 | @Override
151 | public void close() throws IOException {
152 | this.datagramSocket.close();
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/src/main/java/com/cloudbees/syslog/util/CachingReference.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.util;
17 |
18 | import edu.umd.cs.findbugs.annotations.Nullable;
19 | import java.util.concurrent.TimeUnit;
20 | import java.util.concurrent.locks.ReadWriteLock;
21 | import java.util.concurrent.locks.ReentrantReadWriteLock;
22 |
23 | /**
24 | * Maintains a cached version of the {@code Object} that it holds and handle the renewal of this object upon expiration.
25 | *
26 | * Greatly inspired by the {@code CachedData} sample provided in the javadoc
27 | * of {@link java.util.concurrent.locks.ReentrantReadWriteLock}.
28 | *
29 | * {@code Object} is created implementing the {@link #newObject()} method.
30 | *
31 | *
32 | * Sample to get an {@code InetAddress} refreshed against a DNS every 10 seconds:
33 | *
34 | * CachingReference myRemoteServerAddress = new CachingReference<InetAddress>(10, TimeUnit.SECONDS) {
35 | * protected InetAddress newObject() {
36 | * try {
37 | * return InetAddress.getByName(myRemoteServerHostname);
38 | * } catch () {
39 | * throw new RuntimeException("Exception resolving '" + myRemoteServerHostname + "'", e);
40 | * }
41 | * }
42 | * }
43 | *
44 | *
45 | * @author Cyrille Le Clerc
46 | */
47 | public abstract class CachingReference {
48 | private final ReadWriteLock rwl = new ReentrantReadWriteLock();
49 | private long lastCreationInNanos;
50 | private long timeToLiveInNanos;
51 | private E object;
52 |
53 | public CachingReference(long timeToLiveInNanos) {
54 | this.timeToLiveInNanos = timeToLiveInNanos;
55 | }
56 |
57 | public CachingReference(long timeToLive, TimeUnit timeToLiveUnit) {
58 | this(TimeUnit.NANOSECONDS.convert(timeToLive, timeToLiveUnit));
59 | }
60 |
61 | /**
62 | * @return the newly created object.
63 | */
64 | @Nullable
65 | protected abstract E newObject();
66 |
67 | /**
68 | * @return the up to date version of the {@code Object} hold by this reference.
69 | */
70 | @Nullable
71 | public E get() {
72 | rwl.readLock().lock();
73 | try {
74 | if ((System.nanoTime() - lastCreationInNanos) > timeToLiveInNanos) {
75 | // Must release read lock before acquiring write lock
76 | rwl.readLock().unlock();
77 | rwl.writeLock().lock();
78 | try {
79 | // Recheck state because another thread might have
80 | // acquired write lock and changed state before we did.
81 | if ((System.nanoTime() - lastCreationInNanos) > timeToLiveInNanos) {
82 | object = newObject();
83 | lastCreationInNanos = System.nanoTime();
84 | }
85 | } finally {
86 | // Downgrade by acquiring read lock before releasing write lock
87 | rwl.readLock().lock();
88 | rwl.writeLock().unlock();
89 | }
90 | }
91 | return object;
92 | } finally {
93 | rwl.readLock().unlock();
94 | }
95 | }
96 |
97 | @Override
98 | public String toString() {
99 | return "CachingReference[" + this.object + "]";
100 | }
101 | }
102 |
--------------------------------------------------------------------------------
/src/main/java/com/cloudbees/syslog/util/ConcurrentDateFormat.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2014, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.util;
17 |
18 | import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 |
20 | import edu.umd.cs.findbugs.annotations.NonNull;
21 | import java.text.SimpleDateFormat;
22 | import java.util.Date;
23 | import java.util.Locale;
24 | import java.util.TimeZone;
25 | import java.util.concurrent.BlockingQueue;
26 | import java.util.concurrent.LinkedBlockingDeque;
27 |
28 | /**
29 | * Thread safe date formatter.
30 | *
31 | * @author Cyrille Le Clerc
32 | */
33 | public class ConcurrentDateFormat {
34 | private final BlockingQueue dateFormats;
35 | private final String pattern;
36 | private final Locale locale;
37 | private final TimeZone timeZone;
38 |
39 | /**
40 | * Note: This constructor may not support all locales.
41 | * For full coverage, use the factory methods in the {@link java.text.DateFormat}
42 | * class.
43 | *
44 | * @param pattern the pattern describing the date and time pattern
45 | * @param locale the locale whose date pattern symbols should be used
46 | * @param timeZone the timezone used by the underlying calendar
47 | * @param maxCacheSize
48 | * @throws NullPointerException if the given pattern or locale is null
49 | * @throws IllegalArgumentException if the given pattern is invalid
50 | */
51 | public ConcurrentDateFormat(String pattern, Locale locale, TimeZone timeZone, int maxCacheSize) {
52 | this.dateFormats = new LinkedBlockingDeque<>(maxCacheSize);
53 | this.pattern = pattern;
54 | this.locale = locale;
55 | this.timeZone = timeZone;
56 | }
57 |
58 | /**
59 | * Formats a Date into a date/time string.
60 | *
61 | * @param date the time value to be formatted into a time string.
62 | * @return the formatted time string.
63 | */
64 | @NonNull
65 | @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
66 | public String format(@NonNull Date date) {
67 | SimpleDateFormat dateFormat = dateFormats.poll();
68 | if (dateFormat == null) {
69 | dateFormat = new SimpleDateFormat(pattern, locale);
70 | dateFormat.setTimeZone(timeZone);
71 | }
72 | try {
73 | return dateFormat.format(date);
74 | } finally {
75 | dateFormats.offer(dateFormat);
76 | }
77 | }
78 |
79 | @Override
80 | public String toString() {
81 | return "ConcurrentDateFormat[pattern=" + pattern + "]";
82 | }
83 | }
--------------------------------------------------------------------------------
/src/main/java/com/cloudbees/syslog/util/InternalLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2014, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.util;
17 |
18 | import com.cloudbees.syslog.integration.jul.util.LevelHelper;
19 |
20 | import edu.umd.cs.findbugs.annotations.NonNull;
21 | import edu.umd.cs.findbugs.annotations.Nullable;
22 | import java.text.DateFormat;
23 | import java.text.SimpleDateFormat;
24 | import java.util.Date;
25 | import java.util.logging.Level;
26 | import java.util.logging.Logger;
27 |
28 | /**
29 | * 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.
30 | *
31 | * @author Cyrille Le Clerc
32 | */
33 | public class InternalLogger {
34 |
35 | private static Level level;
36 |
37 | static {
38 | try {
39 | level = LevelHelper.findLevel(System.getProperty("com.cloudbees.syslog.debugLevel"));
40 | } catch (RuntimeException e) {
41 | e.printStackTrace();
42 | }
43 | }
44 |
45 | public static InternalLogger getLogger(@NonNull String name) {
46 | return new InternalLogger(name);
47 | }
48 |
49 | public static InternalLogger getLogger(@NonNull Class> clazz) {
50 | return getLogger(clazz.getName());
51 | }
52 |
53 | public static Level getLevel() {
54 | return level;
55 | }
56 |
57 | public static void setLevel(Level level) {
58 | InternalLogger.level = level;
59 | }
60 |
61 | private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
62 | private final String name;
63 | /**
64 | * use java.util.logger to find the logger level if not specified by system property.
65 | */
66 | private final Logger julLogger;
67 |
68 | public InternalLogger(String name) {
69 | this.name = name;
70 | this.julLogger = Logger.getLogger(name);
71 | }
72 |
73 |
74 | public boolean isLoggable(Level level) {
75 | if (level == null)
76 | return false;
77 |
78 | if (this.level == null)
79 | return julLogger.isLoggable(level);
80 |
81 | return level.intValue() >= this.level.intValue();
82 | }
83 |
84 | public void finest(@Nullable String msg) {
85 | log(Level.FINEST, msg);
86 | }
87 |
88 | public void fine(@Nullable String msg) {
89 | log(Level.FINE, msg);
90 | }
91 |
92 | public void finer(@Nullable String msg) {
93 | log(Level.FINER, msg);
94 | }
95 |
96 | public void info(@Nullable String msg) {
97 | log(Level.INFO, msg);
98 | }
99 |
100 | public void log(@Nullable Level level, @Nullable String msg) {
101 | log(level, msg, null);
102 | }
103 |
104 | public void warn(@Nullable String msg) {
105 | log(Level.WARNING, msg);
106 | }
107 |
108 | public void warn(@Nullable String msg, @Nullable Throwable t) {
109 | log(Level.WARNING, msg, t);
110 | }
111 |
112 | /**
113 | * synchronize for the {@link java.text.SimpleDateFormat}.
114 | *
115 | * @param level
116 | * @param msg
117 | * @param t
118 | */
119 | public synchronized void log(@Nullable Level level, @Nullable String msg, @Nullable Throwable t) {
120 | if (!isLoggable(level))
121 | return;
122 | System.err.println(df.format(new Date()) + " [" + Thread.currentThread().getName() + "] " + name + " - " + level.getName() + ": " + msg);
123 | if (t != null)
124 | t.printStackTrace();
125 |
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/main/java/com/cloudbees/syslog/util/IoUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2014, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.util;
17 |
18 | import edu.umd.cs.findbugs.annotations.Nullable;
19 | import java.io.IOException;
20 | import java.io.Writer;
21 | import java.net.Socket;
22 |
23 | /**
24 | * @author Cyrille Le Clerc
25 | */
26 | public class IoUtils {
27 | private IoUtils() {
28 |
29 | }
30 |
31 | public static void closeQuietly(@Nullable Socket socket) {
32 | try {
33 | if (socket != null && !socket.isClosed()) {
34 | socket.close();
35 | }
36 | } catch (Exception e) {
37 | }
38 | }
39 |
40 | /**
41 | * Note: does not {@link java.io.Writer#flush()} before closing.
42 | *
43 | * @param socket
44 | * @param writer
45 | */
46 | public static void closeQuietly(@Nullable Socket socket, @Nullable Writer writer) {
47 | if (writer != null) {
48 | try {
49 | writer.close();
50 | } catch (IOException e) {
51 |
52 | }
53 | }
54 | closeQuietly(socket);
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/SyslogMessageTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog;
17 |
18 | import java.util.Calendar;
19 | import java.util.TimeZone;
20 |
21 | import org.junit.Test;
22 |
23 | import static org.hamcrest.Matchers.is;
24 | import static org.hamcrest.MatcherAssert.assertThat;
25 |
26 | /**
27 | * @author Cyrille Le Clerc
28 | */
29 | public class SyslogMessageTest {
30 |
31 | @Test
32 | public void testRfc5425Format() {
33 | // GIVEN
34 | Calendar cal = Calendar.getInstance();
35 | cal.setTimeZone(TimeZone.getTimeZone("GMT"));
36 | cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
37 | cal.set(Calendar.MILLISECOND, 0);
38 |
39 | System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
40 | System.out.println(cal.getTimeInMillis());
41 |
42 |
43 | SyslogMessage message = new SyslogMessage()
44 | .withTimestamp(cal.getTimeInMillis())
45 | .withAppName("my_app")
46 | .withHostname("myserver.example.com")
47 | .withFacility(Facility.USER)
48 | .withSeverity(Severity.INFORMATIONAL)
49 | .withTimestamp(cal.getTimeInMillis())
50 | .withMsg("a syslog message");
51 |
52 | // WHEN
53 | String actual = message.toRfc5425SyslogMessage();
54 |
55 | // THEN
56 | String expected = "81 <14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - - a syslog message";
57 | assertThat(actual, is(expected));
58 | }
59 |
60 | @Test
61 | public void testRfc5424Format() {
62 |
63 | Calendar cal = Calendar.getInstance();
64 | cal.setTimeZone(TimeZone.getTimeZone("GMT"));
65 | cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
66 | cal.set(Calendar.MILLISECOND, 0);
67 |
68 | System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
69 | System.out.println(cal.getTimeInMillis());
70 |
71 |
72 | SyslogMessage message = new SyslogMessage()
73 | .withTimestamp(cal.getTimeInMillis())
74 | .withAppName("my_app")
75 | .withHostname("myserver.example.com")
76 | .withFacility(Facility.USER)
77 | .withSeverity(Severity.INFORMATIONAL)
78 | .withTimestamp(cal.getTimeInMillis())
79 | .withMsg("a syslog message");
80 |
81 | String actual = message.toRfc5424SyslogMessage();
82 | String expected = "<14>1 2013-12-05T10:30:05.000Z myserver.example.com my_app - - - a syslog message";
83 |
84 | assertThat(actual, is(expected));
85 |
86 | }
87 |
88 | @Test
89 | public void testRfc5424FormatWithStructuredData() {
90 | Calendar cal = Calendar.getInstance();
91 | cal.setTimeZone(TimeZone.getTimeZone("GMT"));
92 | cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
93 | cal.set(Calendar.MILLISECOND, 0);
94 |
95 | System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
96 | System.out.println(cal.getTimeInMillis());
97 |
98 |
99 | SyslogMessage message = new SyslogMessage()
100 | .withTimestamp(cal.getTimeInMillis())
101 | .withAppName("my_app")
102 | .withHostname("myserver.example.com")
103 | .withFacility(Facility.USER)
104 | .withSeverity(Severity.INFORMATIONAL)
105 | .withTimestamp(cal.getTimeInMillis())
106 | .withMsg("a syslog message")
107 | .withSDElement(new SDElement("exampleSDID@32473", new SDParam("iut", "3"), new SDParam("eventSource", "Application"), new SDParam("eventID", "1011")));
108 |
109 | String actual = message.toRfc5424SyslogMessage();
110 | 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";
111 |
112 | assertThat(actual, is(expected));
113 |
114 | message.withSDElement(new SDElement("examplePriority@32473", new SDParam("class", "high")));
115 | actual = message.toRfc5424SyslogMessage();
116 | 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";
117 |
118 | assertThat(actual, is(expected));
119 | }
120 |
121 | @Test
122 | public void testRfc3164Format() {
123 |
124 | Calendar cal = Calendar.getInstance();
125 | cal.setTimeZone(TimeZone.getDefault());
126 | cal.set(2013, Calendar.DECEMBER, 5, 10, 30, 5);
127 | cal.set(Calendar.MILLISECOND, 0);
128 |
129 | System.out.println(SyslogMessage.rfc3339DateFormat.format(cal.getTime()));
130 | System.out.println(cal.getTimeInMillis());
131 |
132 |
133 | SyslogMessage message = new SyslogMessage()
134 | .withTimestamp(cal.getTimeInMillis())
135 | .withAppName("my_app")
136 | .withHostname("myserver.example.com")
137 | .withFacility(Facility.USER)
138 | .withSeverity(Severity.INFORMATIONAL)
139 | .withTimestamp(cal.getTimeInMillis())
140 | .withMsg("a syslog message");
141 |
142 | String actual = message.toRfc3164SyslogMessage();
143 | String expected = "<14>Dec 05 10:30:05 myserver.example.com my_app: a syslog message";
144 |
145 | assertThat(actual, is(expected));
146 |
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/integration/jul/SyslogHandlerTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2010-2013 the original author or authors
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining
5 | * a copy of this software and associated documentation files (the
6 | * "Software"), to deal in the Software without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Software, and to
9 | * permit persons to whom the Software is furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be
13 | * included in all copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 | * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19 | * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20 | * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21 | * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | *
23 | */
24 | package com.cloudbees.syslog.integration.jul;
25 |
26 | import com.cloudbees.syslog.sender.UdpSyslogMessageSender;
27 | import org.junit.Test;
28 |
29 | import java.util.logging.Level;
30 | import java.util.logging.Logger;
31 |
32 | /**
33 | * @author Cyrille Le Clerc
34 | */
35 | public class SyslogHandlerTest {
36 |
37 | @Test
38 | public void test(){
39 | Logger logger = Logger.getLogger(getClass().getName());
40 | logger.setLevel(Level.FINEST);
41 |
42 | UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender();
43 | SyslogHandler syslogHandler = new SyslogHandler(messageSender, Level.ALL, null);
44 |
45 | messageSender.setSyslogServerHostname("cloudbees1.papertrailapp.com");
46 | messageSender.setSyslogServerPort(18977);
47 |
48 | syslogHandler.setMessageHostname("mysecretkey");
49 | syslogHandler.setAppName("SyslogHandlerTest");
50 | logger.addHandler(syslogHandler);
51 |
52 | logger.fine("hello world 2");
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderLoadTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2014, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.sender;
17 |
18 | import com.cloudbees.syslog.Facility;
19 | import com.cloudbees.syslog.Severity;
20 |
21 | import java.io.IOException;
22 | import java.util.Random;
23 | import java.util.concurrent.ExecutorService;
24 | import java.util.concurrent.Executors;
25 | import java.util.concurrent.TimeUnit;
26 | import java.util.concurrent.atomic.AtomicInteger;
27 |
28 | /**
29 | * @author Cyrille Le Clerc
30 | */
31 | public class TcpSyslogMessageSenderLoadTest {
32 |
33 | public static void main(String[] args) throws Exception {
34 | final int THREADS_COUNT = 5;
35 | final int ITERATION_COUNT = 100;
36 |
37 | ExecutorService executorService = Executors.newFixedThreadPool(THREADS_COUNT);
38 |
39 | final TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
40 | messageSender.setDefaultMessageHostname("mysecretkey");
41 | messageSender.setDefaultAppName("myapp");
42 | messageSender.setDefaultFacility(Facility.USER);
43 | messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
44 | messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
45 | // messageSender.setSyslogServerHostname("127.0.0.1");
46 | messageSender.setSyslogServerPort(46022);
47 | messageSender.setSsl(true);
48 |
49 | final AtomicInteger count = new AtomicInteger();
50 |
51 | final Random random = new Random();
52 |
53 | for (int i = 0; i < THREADS_COUNT; i++) {
54 | final String prefix = "thread-" + i + "msg-";
55 |
56 | Runnable command = new Runnable() {
57 | @Override
58 | public void run() {
59 | for (int j = 0; j < ITERATION_COUNT; j++) {
60 | try {
61 | messageSender.sendMessage(prefix + j);
62 | Thread.sleep(random.nextInt(3));
63 | } catch (IOException | InterruptedException e) {
64 | System.err.println("ERROR in " + prefix);
65 | e.printStackTrace();
66 | break;
67 | }
68 | }
69 | }
70 | };
71 |
72 | executorService.execute(command);
73 | }
74 |
75 | executorService.shutdown();
76 | executorService.awaitTermination(1, TimeUnit.MINUTES);
77 | System.out.println("sent " + messageSender.getSendCount() + " in " + messageSender.getSendDurationInMillis() + "ms");
78 | System.out.println("bye");
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/sender/TcpSyslogMessageSenderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.sender;
17 |
18 | import com.cloudbees.syslog.Facility;
19 | import com.cloudbees.syslog.MessageFormat;
20 | import com.cloudbees.syslog.Severity;
21 | import com.cloudbees.syslog.SyslogMessage;
22 | import org.junit.Ignore;
23 | import org.junit.Test;
24 |
25 | import java.sql.Timestamp;
26 |
27 | /**
28 | * @author Cyrille Le Clerc
29 | */
30 | public class TcpSyslogMessageSenderTest {
31 |
32 | // @Ignore
33 | @Test
34 | public void send() throws Exception {
35 | TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
36 | messageSender.setDefaultMessageHostname("mysecretkey");
37 | messageSender.setDefaultAppName("myapp");
38 | messageSender.setDefaultFacility(Facility.USER);
39 | messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
40 | messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
41 | messageSender.setSyslogServerPort(46022);
42 | messageSender.setMessageFormat(MessageFormat.RFC_3164);
43 | messageSender.setSsl(true);
44 | messageSender.sendMessage("unit test message over tcp éèà " + getClass() + " - " + new Timestamp(System.currentTimeMillis()));
45 | }
46 |
47 | @Ignore
48 | @Test
49 | public void send2() throws Exception {
50 |
51 | SyslogMessage msg = new SyslogMessage()
52 | .withAppName("my-app")
53 | .withFacility(Facility.USER)
54 | .withHostname("my-hostname")
55 | .withMsg("my message over tcp éèà " + new Timestamp(System.currentTimeMillis()))
56 | .withSeverity(Severity.INFORMATIONAL)
57 | .withTimestamp(System.currentTimeMillis());
58 |
59 | TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
60 | messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
61 | messageSender.setSyslogServerPort(46022);
62 | messageSender.setMessageFormat(MessageFormat.RFC_3164);
63 | messageSender.setSsl(true);
64 |
65 | System.out.println(msg.toSyslogMessage(messageSender.getMessageFormat()));
66 |
67 | messageSender.sendMessage(msg);
68 | }
69 |
70 |
71 | @Ignore
72 | @Test
73 | public void sendOverSSL() throws Exception {
74 |
75 | SyslogMessage msg = new SyslogMessage()
76 | .withAppName("my-app")
77 | .withFacility(Facility.USER)
78 | .withHostname("my-hostname")
79 | .withMsg("my message over tcp ssl éèà " + new Timestamp(System.currentTimeMillis()))
80 | .withSeverity(Severity.INFORMATIONAL)
81 | .withTimestamp(System.currentTimeMillis());
82 |
83 | TcpSyslogMessageSender messageSender = new TcpSyslogMessageSender();
84 | messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
85 | messageSender.setSyslogServerPort(46022);
86 | messageSender.setMessageFormat(MessageFormat.RFC_3164);
87 | messageSender.setSsl(true);
88 |
89 | System.out.println(msg.toSyslogMessage(messageSender.getMessageFormat()));
90 |
91 | messageSender.sendMessage(msg);
92 | }
93 |
94 |
95 | /**
96 | * https://github.com/CloudBees-community/syslog-java-client/issues/19
97 | */
98 | @Test
99 | public void test_bug19_NullPointerException_In_ToString(){
100 | TcpSyslogMessageSender tcpSyslogMessageSender = new TcpSyslogMessageSender();
101 | tcpSyslogMessageSender.toString();
102 | }
103 | }
104 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/sender/UdpSyslogMessageSenderLoadTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2014, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.sender;
17 |
18 | import com.cloudbees.syslog.Facility;
19 | import com.cloudbees.syslog.Severity;
20 |
21 | import java.io.IOException;
22 | import java.util.concurrent.ExecutorService;
23 | import java.util.concurrent.Executors;
24 | import java.util.concurrent.TimeUnit;
25 | import java.util.concurrent.atomic.AtomicInteger;
26 |
27 | /**
28 | * @author Cyrille Le Clerc
29 | */
30 | public class UdpSyslogMessageSenderLoadTest {
31 |
32 | public static void main(String[] args) throws Exception {
33 | final int THREADS_COUNT = 10;
34 | final int ITERATION_COUNT = 1000;
35 |
36 | ExecutorService executorService = Executors.newFixedThreadPool(THREADS_COUNT);
37 |
38 | final UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender();
39 | messageSender.setDefaultMessageHostname("mysecretkey");
40 | messageSender.setDefaultAppName("myapp");
41 | messageSender.setDefaultFacility(Facility.USER);
42 | messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
43 | messageSender.setSyslogServerHostname("logs2.papertrailapp.com");
44 | // messageSender.setSyslogServerHostname("127.0.0.1");
45 | messageSender.setSyslogServerPort(46022);
46 |
47 | final AtomicInteger count = new AtomicInteger();
48 |
49 |
50 | for (int i = 0; i < THREADS_COUNT; i++) {
51 | final String prefix = "thread-" + i + "-udp-msg-";
52 |
53 | Runnable command = new Runnable() {
54 | @Override
55 | public void run() {
56 | for (int j = 0; j < ITERATION_COUNT; j++) {
57 | try {
58 | messageSender.sendMessage(prefix + j);
59 | } catch (IOException e) {
60 | System.err.println("ERROR in " + prefix);
61 | e.printStackTrace();
62 | break;
63 | }
64 | }
65 | }
66 | };
67 |
68 | executorService.execute(command);
69 | }
70 |
71 | executorService.shutdown();
72 | executorService.awaitTermination(1, TimeUnit.MINUTES);
73 | System.out.println("sent " + messageSender.getSendCount() + " in " + messageSender.getSendDurationInMillis() + "ms");
74 | System.out.println("bye");
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/sender/UpdSyslogMessageSenderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.sender;
17 |
18 | import com.cloudbees.syslog.Facility;
19 | import com.cloudbees.syslog.Severity;
20 | import org.junit.Test;
21 |
22 | import java.sql.Timestamp;
23 |
24 | /**
25 | * @author Cyrille Le Clerc
26 | */
27 | public class UpdSyslogMessageSenderTest {
28 |
29 | // @Ignore
30 | @Test
31 | public void send() throws Exception {
32 | UdpSyslogMessageSender messageSender = new UdpSyslogMessageSender();
33 | messageSender.setDefaultMessageHostname("mysecretkey");
34 | messageSender.setDefaultAppName("myapp");
35 | messageSender.setDefaultFacility(Facility.USER);
36 | messageSender.setDefaultSeverity(Severity.INFORMATIONAL);
37 | // messageSender.setSyslogServerHostname("cloudbees1.papertrailapp.com");
38 | messageSender.setSyslogServerHostname("127.0.0.1");
39 | messageSender.setSyslogServerPort(18977);
40 | messageSender.sendMessage("unit test message éèà " + getClass() + " - " + new Timestamp(System.currentTimeMillis()));
41 | }
42 |
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/test/java/com/cloudbees/syslog/util/CachingReferenceTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2010-2013, CloudBees Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.cloudbees.syslog.util;
17 |
18 | import org.hamcrest.Matchers;
19 | import org.junit.Test;
20 |
21 | import edu.umd.cs.findbugs.annotations.Nullable;
22 | import java.util.concurrent.TimeUnit;
23 |
24 | import static org.hamcrest.MatcherAssert.assertThat;
25 |
26 | public class CachingReferenceTest {
27 | /**
28 | * Test that the locks are properly released.
29 | */
30 | @Test
31 | public void test_return_value() {
32 |
33 | CachingReference cachingReference = new CachingReference(5, TimeUnit.SECONDS) {
34 | @Nullable
35 | @Override
36 | protected String newObject() {
37 | return "value";
38 | }
39 | };
40 |
41 | String actual = cachingReference.get();
42 | assertThat(actual, Matchers.equalTo("value"));
43 | }
44 |
45 | /**
46 | * Test that the locks are properly released.
47 | */
48 | @Test(expected = MyRuntimeException.class)
49 | public void test_throw_exception_in_get_object() {
50 |
51 | CachingReference cachingReference = new CachingReference(5, TimeUnit.SECONDS) {
52 | @Nullable
53 | @Override
54 | protected String newObject() {
55 | throw new MyRuntimeException();
56 | }
57 | };
58 |
59 | cachingReference.get();
60 | }
61 |
62 |
63 | private static class MyRuntimeException extends RuntimeException {
64 | public MyRuntimeException() {
65 | super();
66 | }
67 |
68 | public MyRuntimeException(Throwable cause) {
69 | super(cause);
70 | }
71 |
72 | public MyRuntimeException(String message) {
73 | super(message);
74 | }
75 |
76 | public MyRuntimeException(String message, Throwable cause) {
77 | super(message, cause);
78 | }
79 |
80 | protected MyRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
81 | super(message, cause, enableSuppression, writableStackTrace);
82 | }
83 | }
84 | }
--------------------------------------------------------------------------------