Java tutorial
/** * * The software in this package is published under the terms of the MPL v1.1 license. * * You can get the newest version from http://github.com/neohope * */ package neohope.mule.hl7v2.socket; import java.io.IOException; import java.net.Socket; import neohope.mule.hl7v2.Hl7v2Connector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.pool.KeyedPoolableObjectFactory; import org.mule.util.MapUtils; /** * Creates a client socket using the socket address extracted from the endpoint. Addtional * socket parameters will also be set from the connector */ public abstract class AbstractTcpSocketFactory implements KeyedPoolableObjectFactory { /** * logger used by this class */ private static final Log logger = LogFactory.getLog(Hl7v2SocketFactory.class); public Object makeObject(Object key) throws Exception { Hl7v2SocketKey socketKey = (Hl7v2SocketKey) key; Socket socket = createSocket(socketKey); socket.setReuseAddress(true); Hl7v2Connector connector = socketKey.getConnector(); connector.configureSocket(Hl7v2Connector.CLIENT, socket); return socket; } protected abstract Socket createSocket(Hl7v2SocketKey key) throws IOException; public void destroyObject(Object key, Object object) throws Exception { Socket socket = (Socket) object; if (!socket.isClosed()) { socket.close(); } } public boolean validateObject(Object key, Object object) { Socket socket = (Socket) object; return !socket.isClosed(); } public void activateObject(Object key, Object object) throws Exception { // cannot really activate a Socket } public void passivateObject(Object key, Object object) throws Exception { Hl7v2SocketKey socketKey = (Hl7v2SocketKey) key; boolean keepSocketOpen = MapUtils.getBooleanValue(socketKey.getEndpoint().getProperties(), Hl7v2Connector.KEEP_SEND_SOCKET_OPEN_PROPERTY, socketKey.getConnector().isKeepSendSocketOpen()); Socket socket = (Socket) object; if (!keepSocketOpen) { try { if (socket != null) { socket.close(); } } catch (IOException e) { logger.debug("Failed to close socket after dispatch: " + e.getMessage()); } } } }