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 protected DatagramSocketManager(final String name, final OutputStream os, final InetAddress inetAddress, final String host,
47 final int port, final Layout<? extends Serializable> layout) {
48 super(name, os, inetAddress, host, port, layout);
49 }
50
51
52
53
54
55
56
57
58 public static DatagramSocketManager getSocketManager(final String host, final int port, final Layout<? extends Serializable> layout) {
59 if (Strings.isEmpty(host)) {
60 throw new IllegalArgumentException("A host name is required");
61 }
62 if (port <= 0) {
63 throw new IllegalArgumentException("A port value is required");
64 }
65 return (DatagramSocketManager) getManager("UDP:" + host + ':' + port, new FactoryData(host, port, layout),
66 FACTORY);
67 }
68
69
70
71
72
73
74
75
76
77
78 @Override
79 public Map<String, String> getContentFormat() {
80 final Map<String, String> result = new HashMap<String, String>(super.getContentFormat());
81 result.put("protocol", "udp");
82 result.put("direction", "out");
83 return result;
84 }
85
86
87
88
89 private static class FactoryData {
90 private final String host;
91 private final int port;
92 private final Layout<? extends Serializable> layout;
93
94 public FactoryData(final String host, final int port, final Layout<? extends Serializable> layout) {
95 this.host = host;
96 this.port = port;
97 this.layout = layout;
98 }
99 }
100
101
102
103
104 private static class DatagramSocketManagerFactory implements ManagerFactory<DatagramSocketManager, FactoryData> {
105
106 @Override
107 public DatagramSocketManager createManager(final String name, final FactoryData data) {
108 InetAddress inetAddress;
109 try {
110 inetAddress = InetAddress.getByName(data.host);
111 } catch (final UnknownHostException ex) {
112 LOGGER.error("Could not find address of " + data.host, ex);
113 return null;
114 }
115 final OutputStream os = new DatagramOutputStream(data.host, data.port, data.layout.getHeader(),
116 data.layout.getFooter());
117 return new DatagramSocketManager(name, os, inetAddress, data.host, data.port, data.layout);
118 }
119 }
120 }