1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.impl.io;
29
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.net.Socket;
34 import java.util.concurrent.atomic.AtomicReference;
35
36 import javax.net.ssl.SSLSocket;
37
38 import org.apache.hc.core5.annotation.Internal;
39 import org.apache.hc.core5.util.Args;
40
41
42
43
44
45
46
47 public class SocketHolder {
48
49 private final SSLSocket sslSocket;
50 private final Socket baseSocket;
51 private final AtomicReference<InputStream> inputStreamRef;
52 private final AtomicReference<OutputStream> outputStreamRef;
53
54
55
56
57 public SocketHolder(final SSLSocket sslSocket, final Socket baseSocket) {
58 this.sslSocket = Args.notNull(sslSocket, "SSL Socket");
59 this.baseSocket = Args.notNull(baseSocket, "Socket");
60 this.inputStreamRef = new AtomicReference<>();
61 this.outputStreamRef = new AtomicReference<>();
62 }
63
64 public SocketHolder(final Socket socket) {
65 this.baseSocket = Args.notNull(socket, "Socket");
66 this.sslSocket = null;
67 this.inputStreamRef = new AtomicReference<>();
68 this.outputStreamRef = new AtomicReference<>();
69 }
70
71 public final Socket getSocket() {
72 return sslSocket != null ? sslSocket : baseSocket;
73 }
74
75
76
77
78 @Internal
79 public Socket getBaseSocket() {
80 return baseSocket;
81 }
82
83
84
85
86 @Internal
87 public SSLSocket getSSLSocket() {
88 return sslSocket;
89 }
90
91 public final InputStream getInputStream() throws IOException {
92 InputStream local = inputStreamRef.get();
93 if (local != null) {
94 return local;
95 }
96 local = getInputStream(getSocket());
97 if (inputStreamRef.compareAndSet(null, local)) {
98 return local;
99 }
100 return inputStreamRef.get();
101 }
102
103 protected InputStream getInputStream(final Socket socket) throws IOException {
104 return socket.getInputStream();
105 }
106
107 protected OutputStream getOutputStream(final Socket socket) throws IOException {
108 return socket.getOutputStream();
109 }
110
111 public final OutputStream getOutputStream() throws IOException {
112 OutputStream local = outputStreamRef.get();
113 if (local != null) {
114 return local;
115 }
116 local = getOutputStream(getSocket());
117 if (outputStreamRef.compareAndSet(null, local)) {
118 return local;
119 }
120 return outputStreamRef.get();
121 }
122
123 @Override
124 public String toString() {
125 return "SocketHolder{" +
126 "sslSocket=" + sslSocket +
127 ", baseSocket=" + baseSocket +
128 '}';
129 }
130
131 }