1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.net;
15
16 import java.io.IOException;
17 import java.net.InetAddress;
18 import java.net.Socket;
19
20 import javax.net.SocketFactory;
21
22 import ch.qos.logback.core.util.DelayStrategy;
23 import ch.qos.logback.core.util.FixedDelay;
24
25
26
27
28
29
30
31 public class DefaultSocketConnector implements SocketConnector {
32
33 private final InetAddress address;
34 private final int port;
35 private final DelayStrategy delayStrategy;
36
37 private ExceptionHandler exceptionHandler;
38 private SocketFactory socketFactory;
39
40
41
42
43
44
45
46
47
48 public DefaultSocketConnector(InetAddress address, int port, long initialDelay, long retryDelay) {
49 this(address, port, new FixedDelay(initialDelay, retryDelay));
50 }
51
52
53
54
55
56
57
58
59
60 public DefaultSocketConnector(InetAddress address, int port, DelayStrategy delayStrategy) {
61 this.address = address;
62 this.port = port;
63 this.delayStrategy = delayStrategy;
64 }
65
66
67
68
69
70 public Socket call() throws InterruptedException {
71 useDefaultsForMissingFields();
72 Socket socket = createSocket();
73 while (socket == null && !Thread.currentThread().isInterrupted()) {
74 Thread.sleep(delayStrategy.nextDelay());
75 socket = createSocket();
76 }
77 return socket;
78 }
79
80 private Socket createSocket() {
81 Socket newSocket = null;
82 try {
83 newSocket = socketFactory.createSocket(address, port);
84 } catch (IOException ioex) {
85 exceptionHandler.connectionFailed(this, ioex);
86 }
87 return newSocket;
88 }
89
90 private void useDefaultsForMissingFields() {
91 if (exceptionHandler == null) {
92 exceptionHandler = new ConsoleExceptionHandler();
93 }
94 if (socketFactory == null) {
95 socketFactory = SocketFactory.getDefault();
96 }
97 }
98
99
100
101
102 public void setExceptionHandler(ExceptionHandler exceptionHandler) {
103 this.exceptionHandler = exceptionHandler;
104 }
105
106
107
108
109 public void setSocketFactory(SocketFactory socketFactory) {
110 this.socketFactory = socketFactory;
111 }
112
113
114
115
116 private static class ConsoleExceptionHandler implements ExceptionHandler {
117
118 public void connectionFailed(SocketConnector connector, Exception ex) {
119 System.out.println(ex);
120 }
121
122 }
123
124 }