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.util;
8   
9   import java.net.Socket;
10  import java.net.URL;
11  
12  import org.apache.commons.logging.Log;
13  import org.apache.commons.logging.LogFactory;
14  
15  public final class NetworkUtils
16  {
17      private static final Log logger = LogFactory.getLog(NetworkUtils.class);
18      
19      private NetworkUtils()
20      {
21          // utility class only
22      }
23      
24      public static boolean isServerReachable(URL url, int timeout)
25      {
26          int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
27          return isServerReachable(url.getHost(), port, timeout);
28      }
29      
30      public static boolean isServerReachable(String host, int port, int timeout)
31      {
32          boolean isServerReachable = false;
33          Socket socket = null;
34          
35          try
36          {
37              socket = TimedSocket.createSocket(host, port, timeout);
38              isServerReachable = true;
39          }
40          catch (Exception e)
41          {
42              logger.debug("Server at " + host + ":" + port + " not reachable. " + e.getMessage());
43              try
44              {
45                  if (socket != null)
46                  {
47                      socket.close();
48                  }
49              }
50              catch (Exception socketNotClosed)
51              {
52                  logger.debug(socketNotClosed);
53              }
54          }
55  
56          return isServerReachable;
57      }
58  }