1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.net;
18
19 import java.io.OutputStream;
20 import java.io.Serializable;
21 import java.net.InetAddress;
22 import java.net.UnknownHostException;
23 import java.util.HashMap;
24 import java.util.Map;
25
26 import org.apache.logging.log4j.core.Layout;
27 import org.apache.logging.log4j.core.appender.ManagerFactory;
28 import org.apache.logging.log4j.util.Strings;
29
30
31
32
33 public class DatagramSocketManager extends AbstractSocketManager {
34
35 private static final DatagramSocketManagerFactory FACTORY = new DatagramSocketManagerFactory();
36
37
38
39
40
41
42
43
44
45
46
47 protected DatagramSocketManager(final String name, final OutputStream os, final InetAddress inetAddress, final String host,
48 final int port, final Layout<? extends Serializable> layout, final int bufferSize) {
49 super(name, os, inetAddress, host, port, layout, true, bufferSize);
50 }
51
52
53
54
55
56
57
58
59
60 public static DatagramSocketManager getSocketManager(final String host, final int port,
61 final Layout<? extends Serializable> layout, final int bufferSize) {
62 if (Strings.isEmpty(host)) {
63 throw new IllegalArgumentException("A host name is required");
64 }
65 if (port <= 0) {
66 throw new IllegalArgumentException("A port value is required");
67 }
68 return (DatagramSocketManager) getManager("UDP:" + host + ':' + port,
69 new FactoryData(host, port, layout, bufferSize), FACTORY);
70 }
71
72
73
74
75
76
77
78
79
80
81 @Override
82 public Map<String, String> getContentFormat() {
83 final Map<String, String> result = new HashMap<>(super.getContentFormat());
84 result.put("protocol", "udp");
85 result.put("direction", "out");
86 return result;
87 }
88
89
90
91
92 private static class FactoryData {
93 private final String host;
94 private final int port;
95 private final Layout<? extends Serializable> layout;
96 private final int bufferSize;
97
98 public FactoryData(final String host, final int port, final Layout<? extends Serializable> layout, final int bufferSize) {
99 this.host = host;
100 this.port = port;
101 this.layout = layout;
102 this.bufferSize = bufferSize;
103 }
104 }
105
106
107
108
109 private static class DatagramSocketManagerFactory implements ManagerFactory<DatagramSocketManager, FactoryData> {
110
111 @Override
112 public DatagramSocketManager createManager(final String name, final FactoryData data) {
113 InetAddress inetAddress;
114 try {
115 inetAddress = InetAddress.getByName(data.host);
116 } catch (final UnknownHostException ex) {
117 LOGGER.error("Could not find address of " + data.host, ex);
118 return null;
119 }
120 final OutputStream os = new DatagramOutputStream(data.host, data.port, data.layout.getHeader(),
121 data.layout.getFooter());
122 return new DatagramSocketManager(name, os, inetAddress, data.host, data.port, data.layout, data.bufferSize);
123 }
124 }
125 }