16
16
17
17
package com .mongodb .client .internal ;
18
18
19
+ import com .mongodb .MongoSocketOpenException ;
19
20
import com .mongodb .MongoSocketWriteException ;
20
21
import com .mongodb .ServerAddress ;
21
22
@@ -40,26 +41,52 @@ class KeyManagementService {
40
41
}
41
42
42
43
public InputStream stream (final String host , final ByteBuffer message ) {
44
+ Socket socket ;
45
+ try {
46
+ socket = sslContext .getSocketFactory ().createSocket ();
47
+ } catch (IOException e ) {
48
+ throw new MongoSocketOpenException ("Exception opening connection to Key Management Service" , new ServerAddress (host , port ), e );
49
+ }
50
+
43
51
try {
44
- Socket socket = sslContext .getSocketFactory ().createSocket ();
45
52
socket .setSoTimeout (timeoutMillis );
46
53
socket .connect (new InetSocketAddress (InetAddress .getByName (host ), port ), timeoutMillis );
54
+ } catch (IOException e ) {
55
+ closeSocket (socket );
56
+ throw new MongoSocketOpenException ("Exception opening connection to Key Management Service" , new ServerAddress (host , port ), e );
57
+ }
47
58
59
+ try {
48
60
OutputStream outputStream = socket .getOutputStream ();
49
61
50
62
byte [] bytes = new byte [message .remaining ()];
51
63
52
64
message .get (bytes );
53
65
outputStream .write (bytes );
66
+ } catch (IOException e ) {
67
+ closeSocket (socket );
68
+ throw new MongoSocketWriteException ("Exception sending message to Key Management Service" ,
69
+ new ServerAddress (host , port ), e );
70
+ }
54
71
72
+ try {
55
73
return socket .getInputStream ();
56
-
57
74
} catch (IOException e ) {
58
- throw new MongoSocketWriteException ("Exception sending message to Key Management Service" , new ServerAddress (host , port ), e );
75
+ closeSocket (socket );
76
+ throw new MongoSocketWriteException ("Exception receiving message from Key Management Service" ,
77
+ new ServerAddress (host , port ), e );
59
78
}
60
79
}
61
80
62
81
public int getPort () {
63
82
return port ;
64
83
}
84
+
85
+ private void closeSocket (final Socket socket ) {
86
+ try {
87
+ socket .close ();
88
+ } catch (IOException e ) {
89
+ // ignore
90
+ }
91
+ }
65
92
}
0 commit comments