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.net.InetAddress;
20 import java.net.UnknownHostException;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.apache.logging.log4j.core.Layout;
25 import org.apache.logging.log4j.core.appender.ManagerFactory;
26
27 import java.io.OutputStream;
28
29
30
31
32 public class DatagramSocketManager extends AbstractSocketManager {
33
34 private static final DatagramSocketManagerFactory FACTORY = new DatagramSocketManagerFactory();
35
36
37
38
39
40
41
42
43
44
45 protected DatagramSocketManager(final String name, final OutputStream os, InetAddress address, final String host,
46 final int port, final Layout layout) {
47 super(name, os, address, host, port, layout);
48 }
49
50
51
52
53
54
55
56
57 public static DatagramSocketManager getSocketManager(final String host, final int port, final Layout layout) {
58 if (host == null || host.length() == 0) {
59 throw new IllegalArgumentException("A host name is required");
60 }
61 if (port <= 0) {
62 throw new IllegalArgumentException("A port value is required");
63 }
64 return (DatagramSocketManager) getManager("UDP:" + host + ":" + port, new FactoryData(host, port, layout),
65 FACTORY);
66 }
67
68
69
70
71
72
73
74 @Override
75 public Map<String, String> getContentFormat()
76 {
77 Map<String, String> result = new HashMap<String, String>(super.getContentFormat());
78 result.put("protocol", "udp");
79 result.put("direction", "out");
80
81 return result;
82 }
83
84
85
86
87 private static class FactoryData {
88 private final String host;
89 private final int port;
90 private final Layout layout;
91
92 public FactoryData(final String host, final int port, final Layout layout) {
93 this.host = host;
94 this.port = port;
95 this.layout = layout;
96 }
97 }
98
99
100
101
102 private static class DatagramSocketManagerFactory implements ManagerFactory<DatagramSocketManager, FactoryData> {
103
104 @Override
105 public DatagramSocketManager createManager(final String name, final FactoryData data) {
106 InetAddress address;
107 final OutputStream os = new DatagramOutputStream(data.host, data.port, data.layout.getHeader(),
108 data.layout.getFooter());
109 try {
110 address = 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 return new DatagramSocketManager(name, os, address, data.host, data.port, data.layout);
116 }
117 }
118 }