View Javadoc

1   /*
2    * $Id: NetworkUtils.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.util;
12  
13  import java.net.Socket;
14  import java.net.URL;
15  
16  import org.apache.commons.logging.Log;
17  import org.apache.commons.logging.LogFactory;
18  
19  public final class NetworkUtils
20  {
21      private static final Log logger = LogFactory.getLog(NetworkUtils.class);
22      
23      private NetworkUtils()
24      {
25          // utility class only
26      }
27      
28      public static boolean isServerReachable(URL url, int timeout)
29      {
30          int port = url.getPort() != -1 ? url.getPort() : url.getDefaultPort();
31          return isServerReachable(url.getHost(), port, timeout);
32      }
33      
34      public static boolean isServerReachable(String host, int port, int timeout)
35      {
36          boolean isServerReachable = false;
37          Socket socket = null;
38          
39          try
40          {
41              socket = TimedSocket.createSocket(host, port, timeout);
42              isServerReachable = true;
43          }
44          catch (Exception e)
45          {
46              logger.debug("Server at " + host + ":" + port + " not reachable. " + e.getMessage());
47              try
48              {
49                  if (socket != null)
50                  {
51                      socket.close();
52                  }
53              }
54              catch (Exception socketNotClosed)
55              {
56                  logger.debug(socketNotClosed);
57              }
58          }
59  
60          return isServerReachable;
61      }
62  }