001 /*
002 * Created on 15-Apr-2004
003 */
004 package ca.uhn.hl7v2.protocol.impl;
005
006 import java.io.IOException;
007 import java.io.InputStream;
008 import java.io.OutputStream;
009 import java.net.Socket;
010
011 import ca.uhn.hl7v2.protocol.StreamSource;
012 import ca.uhn.hl7v2.protocol.TransportException;
013
014 /**
015 * A base implementation of <code>StreamSource</code> based on sockets.
016 *
017 * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a>
018 * @version $Revision: 1.1 $ updated on $Date: 2007-02-19 02:24:26 $ by $Author: jamesagnew $
019 */
020 public abstract class SocketStreamSource implements StreamSource {
021
022 /**
023 * @return a socket from which input and output streams for message exchages
024 * are to be obtained
025 */
026 public abstract Socket getSocket();
027
028 /**
029 * Gets fresh instance of socket, which is subsequently available
030 * from <code>getSocket()</code>.
031 */
032 public abstract void connect() throws TransportException;
033
034 /**
035 * Closes streams and underlying socket.
036 * @see ca.uhn.hl7v2.protocol.StreamSource#disconnect()
037 */
038 public void disconnect() throws TransportException {
039 try {
040 if (isConnected()) {
041 getOutboundStream().close();
042 getInboundStream().close();
043 getSocket().close();
044 }
045 } catch (IOException e) {
046 throw new TransportException(e);
047 }
048 }
049
050 /**
051 * @return the stream to which we write outbound messages.
052 */
053 public OutputStream getOutboundStream() throws TransportException {
054 checkConnected();
055 try {
056 return getSocket().getOutputStream();
057 } catch (IOException e) {
058 throw new TransportException(e);
059 }
060 }
061
062 private void checkConnected() throws TransportException {
063 if (!isConnected()) {
064 throw new TransportException("The socket is not connected");
065 }
066 }
067
068 private boolean isConnected() {
069 boolean is = false;
070 if (getSocket() != null && getSocket().isConnected() && !getSocket().isClosed()) {
071 is = true;
072 }
073 return is;
074 }
075
076 /**
077 * @return the stream to which we expect the remote server to send messages.
078 */
079 public InputStream getInboundStream() throws TransportException {
080 checkConnected();
081 try {
082 return getSocket().getInputStream();
083 } catch (IOException e) {
084 throw new TransportException(e);
085 }
086 }
087
088 }