forked from docker-java/docker-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnixSocket.java
More file actions
88 lines (75 loc) · 2.58 KB
/
Copy pathUnixSocket.java
File metadata and controls
88 lines (75 loc) · 2.58 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.github.dockerjava.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.channels.Channels;
import java.nio.channels.SocketChannel;
public class UnixSocket extends AbstractSocket {
/**
* Return a new {@link Socket} for the given path. Will use JDK's {@link java.net.UnixDomainSocketAddress}
* if available and fallback to {@link DomainSocket} otherwise.
*
* @param path the path to the domain socket
* @return a {@link Socket} instance
* @throws IOException if the socket cannot be opened
*/
public static Socket get(String path) throws IOException {
try {
return new UnixSocket(path);
} catch (Exception e) {
//noinspection deprecation
return DomainSocket.get(path);
}
}
private final SocketAddress socketAddress;
private final SocketChannel socketChannel;
private UnixSocket(String path) throws Exception {
Class<?> unixDomainSocketAddress = Class.forName("java.net.UnixDomainSocketAddress");
this.socketAddress =
(SocketAddress) unixDomainSocketAddress.getMethod("of", String.class)
.invoke(null, path);
this.socketChannel = SocketChannel.open(this.socketAddress);
}
@Override
public InputStream getInputStream() throws IOException {
if (isClosed()) {
throw new SocketException("Socket is closed");
}
if (!isConnected()) {
throw new SocketException("Socket is not connected");
}
if (isInputShutdown()) {
throw new SocketException("Socket input is shutdown");
}
return Channels.newInputStream(socketChannel);
}
@Override
public OutputStream getOutputStream() throws IOException {
if (isClosed()) {
throw new SocketException("Socket is closed");
}
if (!isConnected()) {
throw new SocketException("Socket is not connected");
}
if (isOutputShutdown()) {
throw new SocketException("Socket output is shutdown");
}
return Channels.newOutputStream(socketChannel);
}
@Override
public SocketAddress getLocalSocketAddress() {
return socketAddress;
}
@Override
public SocketAddress getRemoteSocketAddress() {
return socketAddress;
}
@Override
public void close() throws IOException {
super.close();
this.socketChannel.close();
}
}