All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.network.NetworkUtils Maven / Gradle / Ivy

The newest version!
package org.springframework.network;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;

public class NetworkUtils {
  private static final Log logger = LogFactory.getLog(NetworkUtils.class);

  public static final String CURRENT_NETWORK_ATTRIBUTE = "currentNetwork";

  private static final Pattern MAC_PATTERN = Pattern.compile("^([0-9a-fA-F]{2}[:\\-\\.]){5}[0-9a-fA-F]{2}$");

  public static Network getCurrentNetwork(HttpServletRequest request) {
    return (Network) request.getAttribute(CURRENT_NETWORK_ATTRIBUTE);
  }

  public static Network getRequiredCurrentNetwork(HttpServletRequest request) {
    Network device = getCurrentNetwork(request);
    if (device == null) {
      throw new IllegalStateException("No currenet network is set in this request and one is required - have you configured a NetworkResolvingHandlerInterceptor?");
    }
    return device;
  }

  public static Network getCurrentNetwork(RequestAttributes attributes) {
    return (Network) attributes.getAttribute(CURRENT_NETWORK_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
  }

  public static boolean isHardwareAddress(String input) {
    return MAC_PATTERN.matcher(input).matches();
  }

  public static InetAddress getByName(String host, long timeout, Executor executor) {
    Future future = new ConcurrentTaskExecutor(executor).submit(new Callable() {
      @Override
      public InetAddress call() throws Exception {
        return InetAddress.getByName(host);
      }
    });
    try {
      return future.get(timeout, TimeUnit.MILLISECONDS);
    }
    catch (TimeoutException | InterruptedException | ExecutionException e) {
      if (e.getCause() instanceof Throwable) {
        if (logger.isTraceEnabled()) {
          logger.trace(e, e.getCause());
        }
        else if (logger.isWarnEnabled()) {
          logger.warn(e.getCause());
        }
      }
      if (logger.isErrorEnabled()) {
        logger.error("host: " + host + ", timeout: " + timeout + ", exception: " + e);
      }
      return InetAddress.getLoopbackAddress();
    }
    finally {
      future.cancel(true);
    }
  }

  public static InetAddress getByName(String host, long timeout) {
    return getByName(host, timeout, null);
  }

  /**
   * {@code byte & 0xFF}
   * @see Integer#toHexString(int)
   */
  private static String getHardwareAddress(InetAddress inetAddress) {
    try {
      Set list = new LinkedHashSet();
      for (byte hardwareAddress : NetworkInterface.getByInetAddress(inetAddress).getHardwareAddress()) {
        list.add(String.format("%02X", hardwareAddress));
      }
      return StringUtils.collectionToDelimitedString(list, ":");
    }
    catch (SocketException e) {
      return null;
    }
  }

  public static Collection getHardwareAddresses() {
    Set collection = new TreeSet();
    for (InetAddress inetAddress : getInetAddresses()) {
      String hardwareAddress = getHardwareAddress(inetAddress);
      if (isHardwareAddress(hardwareAddress)) {
        collection.add(hardwareAddress);
      }
    }
    return collection;
  }

  /**
   * {@code Collections.singleton(null)} 
* {@code while(collection.remove(null))}
* * @see Collection#removeAll(Collection) * @see Collections#singleton(Object) */ public static Collection getHostAddresses() { Set collection = new TreeSet(); for (InetAddress inetAddress : getInetAddresses()) { collection.add(inetAddress.getHostAddress()); } return collection; } /** * @see InetAddress#isLoopbackAddress() * @see InetAddress#isAnyLocalAddress() * @see InetAddress#isLinkLocalAddress() * @see InetAddress#isSiteLocalAddress() */ public static Collection getInetAddresses() { try { Set collection = new LinkedHashSet(); for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) { for (InetAddress inetAddress : Collections.list(networkInterface.getInetAddresses())) { if (!inetAddress.isLoopbackAddress() && !inetAddress.isAnyLocalAddress() && !inetAddress.isLinkLocalAddress()) { collection.add(inetAddress); } } } return collection; } catch (SocketException e) { return Collections.emptySet(); } } public static String getLocalHost() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { return InetAddress.getLoopbackAddress().getHostAddress(); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy