001/*
002 * Created on 15-Apr-2004
003 */
004package ca.uhn.hl7v2.protocol.impl;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.io.OutputStream;
009import java.net.Socket;
010
011import ca.uhn.hl7v2.protocol.StreamSource;
012import 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 */
020public 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}