View Javadoc
1   /*
2    * Created on 15-Apr-2004
3    */
4   package ca.uhn.hl7v2.protocol.impl;
5   
6   import java.io.IOException;
7   import java.io.InputStream;
8   import java.io.OutputStream;
9   import java.net.Socket;
10  
11  import ca.uhn.hl7v2.protocol.StreamSource;
12  import ca.uhn.hl7v2.protocol.TransportException;
13  
14  /**
15   * A base implementation of <code>StreamSource</code> based on sockets. 
16   *  
17   * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a>
18   * @version $Revision: 1.1 $ updated on $Date: 2007-02-19 02:24:26 $ by $Author: jamesagnew $
19   */
20  public abstract class SocketStreamSource implements StreamSource {
21      
22      /**
23       * @return a socket from which input and output streams for message exchages 
24       *      are to be obtained    
25       */
26      public abstract Socket getSocket();
27      
28      /** 
29       * Gets fresh instance of socket, which is subsequently available 
30       * from <code>getSocket()</code>.  
31       */
32      public abstract void connect() throws TransportException;
33  
34      /**
35       * Closes streams and underlying socket. 
36       * @see ca.uhn.hl7v2.protocol.StreamSource#disconnect()
37       */
38      public void disconnect() throws TransportException {
39          try {
40              if (isConnected()) {
41                  getOutboundStream().close();
42                  getInboundStream().close();
43                  getSocket().close();
44              }            
45          } catch (IOException e) {
46              throw new TransportException(e);
47          }
48      }
49      
50      /**
51       * @return the stream to which we write outbound messages.   
52       */
53      public OutputStream getOutboundStream() throws TransportException {
54          checkConnected();
55          try {
56              return getSocket().getOutputStream();
57          } catch (IOException e) {
58              throw new TransportException(e); 
59          }
60      }
61      
62      private void checkConnected() throws TransportException {
63          if (!isConnected()) {
64              throw new TransportException("The socket is not connected");
65          }
66      }
67      
68      private boolean isConnected() {
69          boolean is = false;
70          if (getSocket() != null && getSocket().isConnected() && !getSocket().isClosed()) {
71              is = true;
72          }
73          return is;
74      }
75  
76      /**
77       * @return the stream to which we expect the remote server to send messages.  
78       */
79      public InputStream getInboundStream() throws TransportException {
80          checkConnected();
81          try {
82              return getSocket().getInputStream();
83          } catch (IOException e) {
84              throw new TransportException(e); 
85          }
86      }
87      
88  }