1616
1717package com .mongodb .client .internal ;
1818
19+ import com .mongodb .MongoSocketOpenException ;
1920import com .mongodb .MongoSocketWriteException ;
2021import com .mongodb .ServerAddress ;
2122
@@ -40,26 +41,52 @@ class KeyManagementService {
4041 }
4142
4243 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+
4351 try {
44- Socket socket = sslContext .getSocketFactory ().createSocket ();
4552 socket .setSoTimeout (timeoutMillis );
4653 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+ }
4758
59+ try {
4860 OutputStream outputStream = socket .getOutputStream ();
4961
5062 byte [] bytes = new byte [message .remaining ()];
5163
5264 message .get (bytes );
5365 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+ }
5471
72+ try {
5573 return socket .getInputStream ();
56-
5774 } 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 );
5978 }
6079 }
6180
6281 public int getPort () {
6382 return port ;
6483 }
84+
85+ private void closeSocket (final Socket socket ) {
86+ try {
87+ socket .close ();
88+ } catch (IOException e ) {
89+ // ignore
90+ }
91+ }
6592}
0 commit comments