View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.tcp;
8   
9   import org.mule.util.MapUtils;
10  
11  import java.io.IOException;
12  import java.net.Socket;
13  
14  import org.apache.commons.logging.Log;
15  import org.apache.commons.logging.LogFactory;
16  import org.apache.commons.pool.KeyedPoolableObjectFactory;
17  
18  /**
19   * Creates a client socket using the socket address extracted from the endpoint.  Addtional
20   * socket parameters will also be set from the connector
21   */
22  public abstract class AbstractTcpSocketFactory implements KeyedPoolableObjectFactory
23  {
24  
25      /**
26       * logger used by this class
27       */
28      private static final Log logger = LogFactory.getLog(TcpSocketFactory.class);
29  
30      public Object makeObject(Object key) throws Exception
31      {
32          TcpSocketKey socketKey = (TcpSocketKey) key;
33  
34          Socket socket = createSocket(socketKey);
35          socket.setReuseAddress(true);
36  
37          TcpConnector connector = socketKey.getConnector();
38          connector.configureSocket(TcpConnector.CLIENT, socket);
39  
40          return socket;
41      }
42  
43      protected abstract Socket createSocket(TcpSocketKey key) throws IOException;
44  
45      public void destroyObject(Object key, Object object) throws Exception
46      {
47          Socket socket = (Socket) object;
48          if(!socket.isClosed())
49          {
50              socket.close();
51          }
52      }
53  
54      public boolean validateObject(Object key, Object object)
55      {
56          Socket socket = (Socket) object;
57          return !socket.isClosed();
58      }
59  
60      public void activateObject(Object key, Object object) throws Exception
61      {
62          // cannot really activate a Socket
63      }
64  
65      public void passivateObject(Object key, Object object) throws Exception
66      {
67          TcpSocketKey socketKey = (TcpSocketKey) key;
68  
69          boolean keepSocketOpen = MapUtils.getBooleanValue(socketKey.getEndpoint().getProperties(),
70              TcpConnector.KEEP_SEND_SOCKET_OPEN_PROPERTY, socketKey.getConnector().isKeepSendSocketOpen());
71          Socket socket = (Socket) object;
72  
73          if (!keepSocketOpen)
74          {
75              try
76              {
77                  if (socket != null)
78                  {
79                      socket.close();
80                  }
81              }
82              catch (IOException e)
83              {
84                  logger.debug("Failed to close socket after dispatch: " + e.getMessage());
85              }
86          }
87      }
88  
89  }