一、前言
对于java.net网路地址InetSocketAddress字符串转换、获取有效端口、判断是否本地地址(localhost、127.0.0.1)、根据host及port自定转换为InetSocketAddress地址、ip地址有效校验isValidIP、获取主机名getHostName、InetSocketAddress转换为地址字符串等
二、源码部分
1.PURL类
import java.io.Serializable;@b@import java.io.UnsupportedEncodingException;@b@import java.net.InetSocketAddress;@b@import java.net.MalformedURLException;@b@import java.net.URLDecoder;@b@import java.net.URLEncoder;@b@import java.util.ArrayList;@b@import java.util.Arrays;@b@import java.util.Collection;@b@import java.util.Collections;@b@import java.util.HashMap;@b@import java.util.List;@b@import java.util.Map;@b@import java.util.TreeMap;@b@import java.util.concurrent.ConcurrentHashMap;@b@import java.util.regex.Pattern;@b@@b@public final class PURL implements Serializable {@b@@b@ private static final long serialVersionUID = -1985165475234910535L;@b@@b@ private static final String BACKUP_KEY = "backup";@b@@b@ private static final Pattern COMMA_SPLIT_PATTERN = Pattern@b@ .compile("\\s*[,]+\\s*");@b@@b@ private final String protocol;@b@@b@ private final String username;@b@@b@ private final String password;@b@@b@ private final String host;@b@@b@ private final int port;@b@@b@ private final String path;@b@@b@ private final Map<String, String> parameters;@b@@b@ private volatile transient Map<String, Number> numbers;@b@@b@ private volatile transient Map<String, PURL> urls;@b@@b@ private volatile transient String ip;@b@@b@ private volatile transient String full;@b@@b@ private volatile transient String identity;@b@@b@ private volatile transient String parameter;@b@@b@ private volatile transient String string;@b@@b@ protected PURL() {@b@ this.protocol = null;@b@ this.username = null;@b@ this.password = null;@b@ this.host = null;@b@ this.port = 0;@b@ this.path = null;@b@ this.parameters = null;@b@ }@b@@b@ public PURL(String protocol, String host, int port) {@b@ this(protocol, null, null, host, port, null, (Map<String, String>) null);@b@ }@b@@b@ public PURL(String protocol, String host, int port,@b@ Map<String, String> parameters) {@b@ this(protocol, null, null, host, port, null, parameters);@b@ }@b@@b@ public PURL(String protocol, String host, int port, String path) {@b@ this(protocol, null, null, host, port, path, (Map<String, String>) null);@b@ }@b@@b@ public PURL(String protocol, String host, int port, String path,@b@ Map<String, String> parameters) {@b@ this(protocol, null, null, host, port, path, parameters);@b@ }@b@@b@ public PURL(String protocol, String username, String password, String host,@b@ int port, String path) {@b@ this(protocol, username, password, host, port, path,@b@ (Map<String, String>) null);@b@ }@b@@b@ public PURL(String protocol, String username, String password, String host,@b@ int port, String path, Map<String, String> parameters) {@b@ if ((username == null || username.length() == 0) && password != null@b@ && password.length() > 0) {@b@ throw new IllegalArgumentException(@b@ "Invalid url, password without username!");@b@ }@b@ this.protocol = protocol;@b@ this.username = username;@b@ this.password = password;@b@ this.host = host;@b@ this.port = (port < 0 ? 0 : port);@b@ this.path = path;@b@ // trim the beginning "/"@b@ while (path != null && path.startsWith("/")) {@b@ path = path.substring(1);@b@ }@b@ if (parameters == null) {@b@ parameters = new HashMap<String, String>();@b@ } else {@b@ parameters = new HashMap<String, String>(parameters);@b@ }@b@ this.parameters = Collections.unmodifiableMap(parameters);@b@ }@b@@b@ /**@b@ * Parse url string@b@ * @b@ * @param url@b@ * URL string@b@ * @return URL instance@b@ * @see PURL@b@ */@b@ public static PURL valueOf(String url) {@b@ if (url == null || (url = url.trim()).length() == 0) {@b@ throw new IllegalArgumentException("url == null");@b@ }@b@ String protocol = null;@b@ String username = null;@b@ String password = null;@b@ String host = null;@b@ int port = 0;@b@ String path = null;@b@ Map<String, String> parameters = null;@b@ int i = url.indexOf("?"); // seperator between body and parameters@b@ if (i >= 0) {@b@ String[] parts = url.substring(i + 1).split("\\&");@b@ parameters = new HashMap<String, String>();@b@ for (String part : parts) {@b@ part = part.trim();@b@ if (part.length() > 0) {@b@ int j = part.indexOf('=');@b@ if (j >= 0) {@b@ parameters.put(part.substring(0, j),@b@ part.substring(j + 1));@b@ } else {@b@ parameters.put(part, part);@b@ }@b@ }@b@ }@b@ url = url.substring(0, i);@b@ }@b@ i = url.indexOf("://");@b@ if (i >= 0) {@b@ if (i == 0)@b@ throw new IllegalStateException("url missing protocol: \""@b@ + url + "\"");@b@ protocol = url.substring(0, i);@b@ url = url.substring(i + 3);@b@ } else {@b@ // case: file:/path/to/file.txt@b@ i = url.indexOf(":/");@b@ if (i >= 0) {@b@ if (i == 0)@b@ throw new IllegalStateException("url missing protocol: \""@b@ + url + "\"");@b@ protocol = url.substring(0, i);@b@ url = url.substring(i + 1);@b@ }@b@ }@b@@b@ i = url.indexOf("/");@b@ if (i >= 0) {@b@ path = url.substring(i + 1);@b@ url = url.substring(0, i);@b@ }@b@ i = url.indexOf("@");@b@ if (i >= 0) {@b@ username = url.substring(0, i);@b@ int j = username.indexOf(":");@b@ if (j >= 0) {@b@ password = username.substring(j + 1);@b@ username = username.substring(0, j);@b@ }@b@ url = url.substring(i + 1);@b@ }@b@ i = url.indexOf(":");@b@ if (i >= 0 && i < url.length() - 1) {@b@ port = Integer.parseInt(url.substring(i + 1));@b@ url = url.substring(0, i);@b@ }@b@ if (url.length() > 0)@b@ host = url;@b@ return new PURL(protocol, username, password, host, port, path,@b@ parameters);@b@ }@b@@b@ public String getProtocol() {@b@ return protocol;@b@ }@b@@b@ public String getUsername() {@b@ return username;@b@ }@b@@b@ public String getPassword() {@b@ return password;@b@ }@b@@b@ public String getAuthority() {@b@ if ((username == null || username.length() == 0)@b@ && (password == null || password.length() == 0)) {@b@ return null;@b@ }@b@ return (username == null ? "" : username) + ":"@b@ + (password == null ? "" : password);@b@ }@b@@b@ public String getHost() {@b@ return host;@b@ }@b@@b@ /**@b@ * 获取IP地址.@b@ * @b@ * 否则配置域名会有问题@b@ * @b@ * @return ip@b@ */@b@ public String getIp() {@b@ if (ip == null) {@b@ ip = PNetUtils.getIpByHost(host);@b@ }@b@ return ip;@b@ }@b@@b@ public int getPort() {@b@ return port;@b@ }@b@@b@ public int getPort(int defaultPort) {@b@ return port <= 0 ? defaultPort : port;@b@ }@b@@b@ public String getAddress() {@b@ return port <= 0 ? host : host + ":" + port;@b@ }@b@@b@ public String getBackupAddress() {@b@ return getBackupAddress(0);@b@ }@b@@b@ public String getBackupAddress(int defaultPort) {@b@ StringBuilder address = new StringBuilder(appendDefaultPort(@b@ getAddress(), defaultPort));@b@ String[] backups = getParameter(BACKUP_KEY, new String[0]);@b@ if (backups != null && backups.length > 0) {@b@ for (String backup : backups) {@b@ address.append(",");@b@ address.append(appendDefaultPort(backup, defaultPort));@b@ }@b@ }@b@ return address.toString();@b@ }@b@@b@ public List<PURL> getBackupUrls() {@b@ List<PURL> urls = new ArrayList<PURL>();@b@ urls.add(this);@b@ String[] backups = getParameter(BACKUP_KEY, new String[0]);@b@ if (backups != null && backups.length > 0) {@b@ for (String backup : backups) {@b@ urls.add(this.setAddress(backup));@b@ }@b@ }@b@ return urls;@b@ }@b@@b@ private String appendDefaultPort(String address, int defaultPort) {@b@ if (address != null && address.length() > 0 && defaultPort > 0) {@b@ int i = address.indexOf(':');@b@ if (i < 0) {@b@ return address + ":" + defaultPort;@b@ } else if (Integer.parseInt(address.substring(i + 1)) == 0) {@b@ return address.substring(0, i + 1) + defaultPort;@b@ }@b@ }@b@ return address;@b@ }@b@@b@ public String getPath() {@b@ return path;@b@ }@b@@b@ public String getAbsolutePath() {@b@ if (path != null && !path.startsWith("/")) {@b@ return "/" + path;@b@ }@b@ return path;@b@ }@b@@b@ public PURL setProtocol(String protocol) {@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public PURL setUsername(String username) {@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public PURL setPassword(String password) {@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public PURL setAddress(String address) {@b@ int i = address.lastIndexOf(':');@b@ String host;@b@ int port = this.port;@b@ if (i >= 0) {@b@ host = address.substring(0, i);@b@ port = Integer.parseInt(address.substring(i + 1));@b@ } else {@b@ host = address;@b@ }@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public PURL setHost(String host) {@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public PURL setPort(int port) {@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public PURL setPath(String path) {@b@ return new PURL(protocol, username, password, host, port, path,@b@ getParameters());@b@ }@b@@b@ public Map<String, String> getParameters() {@b@ return parameters;@b@ }@b@@b@ public String getParameterAndDecoded(String key) {@b@ return getParameterAndDecoded(key, null);@b@ }@b@@b@ public String getParameterAndDecoded(String key, String defaultValue) {@b@ return decode(getParameter(key, defaultValue));@b@ }@b@@b@ public String getParameter(String key) {@b@ return parameters.get(key);@b@ }@b@@b@ public String getParameter(String key, String defaultValue) {@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public String[] getParameter(String key, String[] defaultValue) {@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return COMMA_SPLIT_PATTERN.split(value);@b@ }@b@@b@ private Map<String, Number> getNumbers() {@b@ if (numbers == null) { // 允许并发重复创建@b@ numbers = new ConcurrentHashMap<String, Number>();@b@ }@b@ return numbers;@b@ }@b@@b@ private Map<String, PURL> getUrls() {@b@ if (urls == null) { // 允许并发重复创建@b@ urls = new ConcurrentHashMap<String, PURL>();@b@ }@b@ return urls;@b@ }@b@@b@ public PURL getUrlParameter(String key) {@b@ PURL u = getUrls().get(key);@b@ if (u != null) {@b@ return u;@b@ }@b@ String value = getParameterAndDecoded(key);@b@ if (value == null || value.length() == 0) {@b@ return null;@b@ }@b@ u = PURL.valueOf(value);@b@ getUrls().put(key, u);@b@ return u;@b@ }@b@@b@ public double getParameter(String key, double defaultValue) {@b@ Number n = getNumbers().get(key);@b@ if (n != null) {@b@ return n.doubleValue();@b@ }@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ double d = Double.parseDouble(value);@b@ getNumbers().put(key, d);@b@ return d;@b@ }@b@@b@ public float getParameter(String key, float defaultValue) {@b@ Number n = getNumbers().get(key);@b@ if (n != null) {@b@ return n.floatValue();@b@ }@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ float f = Float.parseFloat(value);@b@ getNumbers().put(key, f);@b@ return f;@b@ }@b@@b@ public long getParameter(String key, long defaultValue) {@b@ Number n = getNumbers().get(key);@b@ if (n != null) {@b@ return n.longValue();@b@ }@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ long l = Long.parseLong(value);@b@ getNumbers().put(key, l);@b@ return l;@b@ }@b@@b@ public int getParameter(String key, int defaultValue) {@b@ Number n = getNumbers().get(key);@b@ if (n != null) {@b@ return n.intValue();@b@ }@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ int i = Integer.parseInt(value);@b@ getNumbers().put(key, i);@b@ return i;@b@ }@b@@b@ public short getParameter(String key, short defaultValue) {@b@ Number n = getNumbers().get(key);@b@ if (n != null) {@b@ return n.shortValue();@b@ }@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ short s = Short.parseShort(value);@b@ getNumbers().put(key, s);@b@ return s;@b@ }@b@@b@ public byte getParameter(String key, byte defaultValue) {@b@ Number n = getNumbers().get(key);@b@ if (n != null) {@b@ return n.byteValue();@b@ }@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ byte b = Byte.parseByte(value);@b@ getNumbers().put(key, b);@b@ return b;@b@ }@b@@b@ public float getPositiveParameter(String key, float defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ float value = getParameter(key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public double getPositiveParameter(String key, double defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ double value = getParameter(key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public long getPositiveParameter(String key, long defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ long value = getParameter(key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public int getPositiveParameter(String key, int defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ int value = getParameter(key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public short getPositiveParameter(String key, short defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ short value = getParameter(key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public byte getPositiveParameter(String key, byte defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ byte value = getParameter(key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public char getParameter(String key, char defaultValue) {@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return value.charAt(0);@b@ }@b@@b@ public boolean getParameter(String key, boolean defaultValue) {@b@ String value = getParameter(key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return Boolean.parseBoolean(value);@b@ }@b@@b@ public boolean hasParameter(String key) {@b@ String value = getParameter(key);@b@ return value != null && value.length() > 0;@b@ }@b@@b@ public String getMethodParameterAndDecoded(String method, String key) {@b@ return PURL.decode(getMethodParameter(method, key));@b@ }@b@@b@ public String getMethodParameterAndDecoded(String method, String key,@b@ String defaultValue) {@b@ return PURL.decode(getMethodParameter(method, key, defaultValue));@b@ }@b@@b@ public String getMethodParameter(String method, String key) {@b@ String value = parameters.get(method + "." + key);@b@ if (value == null || value.length() == 0) {@b@ return getParameter(key);@b@ }@b@ return value;@b@ }@b@@b@ public String getMethodParameter(String method, String key,@b@ String defaultValue) {@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public double getMethodParameter(String method, String key,@b@ double defaultValue) {@b@ String methodKey = method + "." + key;@b@ Number n = getNumbers().get(methodKey);@b@ if (n != null) {@b@ return n.intValue();@b@ }@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ double d = Double.parseDouble(value);@b@ getNumbers().put(methodKey, d);@b@ return d;@b@ }@b@@b@ public float getMethodParameter(String method, String key,@b@ float defaultValue) {@b@ String methodKey = method + "." + key;@b@ Number n = getNumbers().get(methodKey);@b@ if (n != null) {@b@ return n.intValue();@b@ }@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ float f = Float.parseFloat(value);@b@ getNumbers().put(methodKey, f);@b@ return f;@b@ }@b@@b@ public long getMethodParameter(String method, String key, long defaultValue) {@b@ String methodKey = method + "." + key;@b@ Number n = getNumbers().get(methodKey);@b@ if (n != null) {@b@ return n.intValue();@b@ }@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ long l = Long.parseLong(value);@b@ getNumbers().put(methodKey, l);@b@ return l;@b@ }@b@@b@ public int getMethodParameter(String method, String key, int defaultValue) {@b@ String methodKey = method + "." + key;@b@ Number n = getNumbers().get(methodKey);@b@ if (n != null) {@b@ return n.intValue();@b@ }@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ int i = Integer.parseInt(value);@b@ getNumbers().put(methodKey, i);@b@ return i;@b@ }@b@@b@ public short getMethodParameter(String method, String key,@b@ short defaultValue) {@b@ String methodKey = method + "." + key;@b@ Number n = getNumbers().get(methodKey);@b@ if (n != null) {@b@ return n.shortValue();@b@ }@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ short s = Short.parseShort(value);@b@ getNumbers().put(methodKey, s);@b@ return s;@b@ }@b@@b@ public byte getMethodParameter(String method, String key, byte defaultValue) {@b@ String methodKey = method + "." + key;@b@ Number n = getNumbers().get(methodKey);@b@ if (n != null) {@b@ return n.byteValue();@b@ }@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ byte b = Byte.parseByte(value);@b@ getNumbers().put(methodKey, b);@b@ return b;@b@ }@b@@b@ public double getMethodPositiveParameter(String method, String key,@b@ double defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ double value = getMethodParameter(method, key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public float getMethodPositiveParameter(String method, String key,@b@ float defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ float value = getMethodParameter(method, key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public long getMethodPositiveParameter(String method, String key,@b@ long defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ long value = getMethodParameter(method, key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public int getMethodPositiveParameter(String method, String key,@b@ int defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ int value = getMethodParameter(method, key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public short getMethodPositiveParameter(String method, String key,@b@ short defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ short value = getMethodParameter(method, key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public byte getMethodPositiveParameter(String method, String key,@b@ byte defaultValue) {@b@ if (defaultValue <= 0) {@b@ throw new IllegalArgumentException("defaultValue <= 0");@b@ }@b@ byte value = getMethodParameter(method, key, defaultValue);@b@ if (value <= 0) {@b@ return defaultValue;@b@ }@b@ return value;@b@ }@b@@b@ public char getMethodParameter(String method, String key, char defaultValue) {@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return value.charAt(0);@b@ }@b@@b@ public boolean getMethodParameter(String method, String key,@b@ boolean defaultValue) {@b@ String value = getMethodParameter(method, key);@b@ if (value == null || value.length() == 0) {@b@ return defaultValue;@b@ }@b@ return Boolean.parseBoolean(value);@b@ }@b@@b@ public boolean hasMethodParameter(String method, String key) {@b@ if (method == null) {@b@ String suffix = "." + key;@b@ for (String fullKey : parameters.keySet()) {@b@ if (fullKey.endsWith(suffix)) {@b@ return true;@b@ }@b@ }@b@ return false;@b@ }@b@ if (key == null) {@b@ String prefix = method + ".";@b@ for (String fullKey : parameters.keySet()) {@b@ if (fullKey.startsWith(prefix)) {@b@ return true;@b@ }@b@ }@b@ return false;@b@ }@b@ String value = getMethodParameter(method, key);@b@ return value != null && value.length() > 0;@b@ }@b@@b@ public boolean isLocalHost() {@b@ return PNetUtils.isLocalHost(host) || getParameter("localhost", false);@b@ }@b@@b@ public PURL addParameterAndEncoded(String key, String value) {@b@ if (value == null || value.length() == 0) {@b@ return this;@b@ }@b@ return addParameter(key, encode(value));@b@ }@b@@b@ public PURL addParameter(String key, boolean value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, char value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, byte value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, short value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, int value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, long value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, float value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, double value) {@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, Enum<?> value) {@b@ if (value == null)@b@ return this;@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, Number value) {@b@ if (value == null)@b@ return this;@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, CharSequence value) {@b@ if (value == null || value.length() == 0)@b@ return this;@b@ return addParameter(key, String.valueOf(value));@b@ }@b@@b@ public PURL addParameter(String key, String value) {@b@ if (key == null || key.length() == 0 || value == null@b@ || value.length() == 0) {@b@ return this;@b@ }@b@ // 如果没有修改,直接返回@b@ if (value.equals(getParameters().get(key))) { // value != null@b@ return this;@b@ }@b@@b@ Map<String, String> map = new HashMap<String, String>(getParameters());@b@ map.put(key, value);@b@ return new PURL(protocol, username, password, host, port, path, map);@b@ }@b@@b@ public PURL addParameterIfAbsent(String key, String value) {@b@ if (key == null || key.length() == 0 || value == null@b@ || value.length() == 0) {@b@ return this;@b@ }@b@ if (hasParameter(key)) {@b@ return this;@b@ }@b@ Map<String, String> map = new HashMap<String, String>(getParameters());@b@ map.put(key, value);@b@ return new PURL(protocol, username, password, host, port, path, map);@b@ }@b@@b@ /**@b@ * Add parameters to a new url.@b@ * @b@ * @param parameters@b@ * @return A new URL@b@ */@b@ public PURL addParameters(Map<String, String> parameters) {@b@ if (parameters == null || parameters.size() == 0) {@b@ return this;@b@ }@b@@b@ boolean hasAndEqual = true;@b@ for (Map.Entry<String, String> entry : parameters.entrySet()) {@b@ String value = getParameters().get(entry.getKey());@b@ if (value == null && entry.getValue() != null@b@ || !value.equals(entry.getValue())) {@b@ hasAndEqual = false;@b@ break;@b@ }@b@ }@b@ // 如果没有修改,直接返回@b@ if (hasAndEqual)@b@ return this;@b@@b@ Map<String, String> map = new HashMap<String, String>(getParameters());@b@ map.putAll(parameters);@b@ return new PURL(protocol, username, password, host, port, path, map);@b@ }@b@@b@ public PURL addParametersIfAbsent(Map<String, String> parameters) {@b@ if (parameters == null || parameters.size() == 0) {@b@ return this;@b@ }@b@ Map<String, String> map = new HashMap<String, String>(parameters);@b@ map.putAll(getParameters());@b@ return new PURL(protocol, username, password, host, port, path, map);@b@ }@b@@b@ public PURL addParameters(String... pairs) {@b@ if (pairs == null || pairs.length == 0) {@b@ return this;@b@ }@b@ if (pairs.length % 2 != 0) {@b@ throw new IllegalArgumentException(@b@ "Map pairs can not be odd number.");@b@ }@b@ Map<String, String> map = new HashMap<String, String>();@b@ int len = pairs.length / 2;@b@ for (int i = 0; i < len; i++) {@b@ map.put(pairs[2 * i], pairs[2 * i + 1]);@b@ }@b@ return addParameters(map);@b@ }@b@@b@ public PURL removeParameter(String key) {@b@ if (key == null || key.length() == 0) {@b@ return this;@b@ }@b@ return removeParameters(key);@b@ }@b@@b@ public PURL removeParameters(Collection<String> keys) {@b@ if (keys == null || keys.size() == 0) {@b@ return this;@b@ }@b@ return removeParameters(keys.toArray(new String[0]));@b@ }@b@@b@ public PURL removeParameters(String... keys) {@b@ if (keys == null || keys.length == 0) {@b@ return this;@b@ }@b@ Map<String, String> map = new HashMap<String, String>(getParameters());@b@ for (String key : keys) {@b@ map.remove(key);@b@ }@b@ if (map.size() == getParameters().size()) {@b@ return this;@b@ }@b@ return new PURL(protocol, username, password, host, port, path, map);@b@ }@b@@b@ public PURL clearParameters() {@b@ return new PURL(protocol, username, password, host, port, path,@b@ new HashMap<String, String>());@b@ }@b@@b@ public String getRawParameter(String key) {@b@ if ("protocol".equals(key))@b@ return protocol;@b@ if ("username".equals(key))@b@ return username;@b@ if ("password".equals(key))@b@ return password;@b@ if ("host".equals(key))@b@ return host;@b@ if ("port".equals(key))@b@ return String.valueOf(port);@b@ if ("path".equals(key))@b@ return path;@b@ return getParameter(key);@b@ }@b@@b@ public Map<String, String> toMap() {@b@ Map<String, String> map = new HashMap<String, String>(parameters);@b@ if (protocol != null)@b@ map.put("protocol", protocol);@b@ if (username != null)@b@ map.put("username", username);@b@ if (password != null)@b@ map.put("password", password);@b@ if (host != null)@b@ map.put("host", host);@b@ if (port > 0)@b@ map.put("port", String.valueOf(port));@b@ if (path != null)@b@ map.put("path", path);@b@ return map;@b@ }@b@@b@ public String toString() {@b@ if (string != null) {@b@ return string;@b@ }@b@ return string = buildString(false, true); // no show username and@b@ // password@b@ }@b@@b@ public String toString(String... parameters) {@b@ return buildString(false, true, parameters); // no show username and@b@ // password@b@ }@b@@b@ public String toIdentityString() {@b@ if (identity != null) {@b@ return identity;@b@ }@b@ return identity = buildString(true, false); // only return identity@b@ // message, see the method@b@ // "equals" and "hashCode"@b@ }@b@@b@ public String toIdentityString(String... parameters) {@b@ return buildString(true, false, parameters); // only return identity@b@ // message, see the@b@ // method "equals" and@b@ // "hashCode"@b@ }@b@@b@ public String toFullString() {@b@ if (full != null) {@b@ return full;@b@ }@b@ return full = buildString(true, true);@b@ }@b@@b@ public String toFullString(String... parameters) {@b@ return buildString(true, true, parameters);@b@ }@b@@b@ public String toParameterString() {@b@ if (parameter != null) {@b@ return parameter;@b@ }@b@ return parameter = toParameterString(new String[0]);@b@ }@b@@b@ public String toParameterString(String... parameters) {@b@ StringBuilder buf = new StringBuilder();@b@ buildParameters(buf, false, parameters);@b@ return buf.toString();@b@ }@b@@b@ private void buildParameters(StringBuilder buf, boolean concat,@b@ String[] parameters) {@b@ if (getParameters() != null && getParameters().size() > 0) {@b@ List<String> includes = (parameters == null@b@ || parameters.length == 0 ? null : Arrays@b@ .asList(parameters));@b@ boolean first = true;@b@ for (Map.Entry<String, String> entry : new TreeMap<String, String>(@b@ getParameters()).entrySet()) {@b@ if (entry.getKey() != null@b@ && entry.getKey().length() > 0@b@ && (includes == null || includes.contains(entry@b@ .getKey()))) {@b@ if (first) {@b@ if (concat) {@b@ buf.append("?");@b@ }@b@ first = false;@b@ } else {@b@ buf.append("&");@b@ }@b@ buf.append(entry.getKey());@b@ buf.append("=");@b@ buf.append(entry.getValue() == null ? "" : entry.getValue()@b@ .trim());@b@ }@b@ }@b@ }@b@ }@b@@b@ private String buildString(boolean appendUser, boolean appendParameter,@b@ String... parameters) {@b@ return buildString(appendUser, appendParameter, false, parameters);@b@ }@b@@b@ private String buildString(boolean appendUser, boolean appendParameter,@b@ boolean useIP, String... parameters) {@b@ StringBuilder buf = new StringBuilder();@b@ if (protocol != null && protocol.length() > 0) {@b@ buf.append(protocol);@b@ buf.append("://");@b@ }@b@ if (appendUser && username != null && username.length() > 0) {@b@ buf.append(username);@b@ if (password != null && password.length() > 0) {@b@ buf.append(":");@b@ buf.append(password);@b@ }@b@ buf.append("@");@b@ }@b@ String host;@b@ if (useIP) {@b@ host = getIp();@b@ } else {@b@ host = getHost();@b@ }@b@ if (host != null && host.length() > 0) {@b@ buf.append(host);@b@ if (port > 0) {@b@ buf.append(":");@b@ buf.append(port);@b@ }@b@ }@b@ String path = getPath();@b@ if (path != null && path.length() > 0) {@b@ buf.append("/");@b@ buf.append(path);@b@ }@b@ if (appendParameter) {@b@ buildParameters(buf, true, parameters);@b@ }@b@ return buf.toString();@b@ }@b@@b@ public java.net.URL toJavaURL() {@b@ try {@b@ return new java.net.URL(toString());@b@ } catch (MalformedURLException e) {@b@ throw new IllegalStateException(e.getMessage(), e);@b@ }@b@ }@b@@b@ public InetSocketAddress toInetSocketAddress() {@b@ return new InetSocketAddress(host, port);@b@ }@b@@b@ public static String encode(String value) {@b@ if (value == null || value.length() == 0) {@b@ return "";@b@ }@b@ try {@b@ return URLEncoder.encode(value, "UTF-8");@b@ } catch (UnsupportedEncodingException e) {@b@ throw new RuntimeException(e.getMessage(), e);@b@ }@b@ }@b@@b@ public static String decode(String value) {@b@ if (value == null || value.length() == 0) {@b@ return "";@b@ }@b@ try {@b@ return URLDecoder.decode(value, "UTF-8");@b@ } catch (UnsupportedEncodingException e) {@b@ throw new RuntimeException(e.getMessage(), e);@b@ }@b@ }@b@@b@ @Override@b@ public int hashCode() {@b@ final int prime = 31;@b@ int result = 1;@b@ result = prime * result + ((host == null) ? 0 : host.hashCode());@b@ result = prime * result@b@ + ((parameters == null) ? 0 : parameters.hashCode());@b@ result = prime * result@b@ + ((password == null) ? 0 : password.hashCode());@b@ result = prime * result + ((path == null) ? 0 : path.hashCode());@b@ result = prime * result + port;@b@ result = prime * result@b@ + ((protocol == null) ? 0 : protocol.hashCode());@b@ result = prime * result@b@ + ((username == null) ? 0 : username.hashCode());@b@ return result;@b@ }@b@@b@ @Override@b@ public boolean equals(Object obj) {@b@ if (this == obj)@b@ return true;@b@ if (obj == null)@b@ return false;@b@ if (getClass() != obj.getClass())@b@ return false;@b@ PURL other = (PURL) obj;@b@ if (host == null) {@b@ if (other.host != null)@b@ return false;@b@ } else if (!host.equals(other.host))@b@ return false;@b@ if (parameters == null) {@b@ if (other.parameters != null)@b@ return false;@b@ } else if (!parameters.equals(other.parameters))@b@ return false;@b@ if (password == null) {@b@ if (other.password != null)@b@ return false;@b@ } else if (!password.equals(other.password))@b@ return false;@b@ if (path == null) {@b@ if (other.path != null)@b@ return false;@b@ } else if (!path.equals(other.path))@b@ return false;@b@ if (port != other.port)@b@ return false;@b@ if (protocol == null) {@b@ if (other.protocol != null)@b@ return false;@b@ } else if (!protocol.equals(other.protocol))@b@ return false;@b@ if (username == null) {@b@ if (other.username != null)@b@ return false;@b@ } else if (!username.equals(other.username))@b@ return false;@b@ return true;@b@ }@b@@b@}
2.PNetUtils工具类
import java.io.IOException;@b@import java.net.InetAddress;@b@import java.net.InetSocketAddress;@b@import java.net.NetworkInterface;@b@import java.net.ServerSocket;@b@import java.net.UnknownHostException;@b@import java.util.Enumeration;@b@import java.util.Map;@b@import java.util.Random;@b@import java.util.regex.Pattern;@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@import com.alibaba.dubbo.common.utils.LRUCache;@b@@b@public class PNetUtils {@b@@b@ private static final Log logger = LogFactory.getLog(PNetUtils.class);@b@@b@ public static final String LOCALHOST = "127.0.0.1";@b@@b@ public static final String ANYHOST = "0.0.0.0";@b@@b@ private static final int RND_PORT_START = 30000;@b@@b@ private static final int RND_PORT_RANGE = 10000;@b@@b@ private static final Random RANDOM = new Random(System.nanoTime());@b@@b@ public static int getRandomPort() {@b@ return RND_PORT_START + RANDOM.nextInt(RND_PORT_RANGE);@b@ }@b@@b@ public static int getAvailablePort() {@b@ ServerSocket ss = null;@b@ try {@b@ ss = new ServerSocket();@b@ ss.bind(null);@b@ return ss.getLocalPort();@b@ } catch (IOException e) {@b@ return getRandomPort();@b@ } finally {@b@ if (ss != null) {@b@ try {@b@ ss.close();@b@ } catch (IOException e) {@b@ }@b@ }@b@ }@b@ }@b@@b@ public static int getAvailablePort(int port) {@b@ if (port <= 0) {@b@ return getAvailablePort();@b@ }@b@ for (int i = port; i < MAX_PORT; i++) {@b@ ServerSocket ss = null;@b@ try {@b@ ss = new ServerSocket(i);@b@ return i;@b@ } catch (IOException e) {@b@ // continue@b@ } finally {@b@ if (ss != null) {@b@ try {@b@ ss.close();@b@ } catch (IOException e) {@b@ }@b@ }@b@ }@b@ }@b@ return port;@b@ }@b@@b@ private static final int MIN_PORT = 0;@b@@b@ private static final int MAX_PORT = 65535;@b@@b@ public static boolean isInvalidPort(int port) {@b@ return port > MIN_PORT || port <= MAX_PORT;@b@ }@b@@b@ private static final Pattern ADDRESS_PATTERN = Pattern@b@ .compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");@b@@b@ public static boolean isValidAddress(String address) {@b@ return ADDRESS_PATTERN.matcher(address).matches();@b@ }@b@@b@ private static final Pattern LOCAL_IP_PATTERN = Pattern@b@ .compile("127(\\.\\d{1,3}){3}$");@b@@b@ public static boolean isLocalHost(String host) {@b@ return host != null@b@ && (LOCAL_IP_PATTERN.matcher(host).matches() || host@b@ .equalsIgnoreCase("localhost"));@b@ }@b@@b@ public static boolean isAnyHost(String host) {@b@ return "0.0.0.0".equals(host);@b@ }@b@@b@ public static boolean isInvalidLocalHost(String host) {@b@ return host == null || host.length() == 0@b@ || host.equalsIgnoreCase("localhost") || host.equals("0.0.0.0")@b@ || (LOCAL_IP_PATTERN.matcher(host).matches());@b@ }@b@@b@ public static boolean isValidLocalHost(String host) {@b@ return !isInvalidLocalHost(host);@b@ }@b@@b@ public static InetSocketAddress getLocalSocketAddress(String host, int port) {@b@ return isInvalidLocalHost(host) ? new InetSocketAddress(port)@b@ : new InetSocketAddress(host, port);@b@ }@b@@b@ private static final Pattern IP_PATTERN = Pattern@b@ .compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");@b@@b@ public static boolean isValidAddress(InetAddress address) {@b@ if (address == null || address.isLoopbackAddress())@b@ return false;@b@ String name = address.getHostAddress();@b@ return (name != null && !ANYHOST.equals(name)@b@ && !LOCALHOST.equals(name) && IP_PATTERN.matcher(name)@b@ .matches());@b@ }@b@@b@ public static boolean isValidIP(String ip) {@b@ if (ip == null)@b@ return false;@b@ return (ip != null && !ANYHOST.equals(ip) && !LOCALHOST.equals(ip) && IP_PATTERN@b@ .matcher(ip).matches());@b@ }@b@@b@ public static String getLocalHost() {@b@ InetAddress address = getLocalAddress();@b@ return address == null ? LOCALHOST : address.getHostAddress();@b@ }@b@@b@ public static String filterLocalHost(String host) {@b@ if (host == null || host.length() == 0) {@b@ return host;@b@ }@b@ if (host.contains("://")) {@b@ PURL u = PURL.valueOf(host);@b@ if (PNetUtils.isInvalidLocalHost(u.getHost())) {@b@ return u.setHost(PNetUtils.getLocalHost()).toFullString();@b@ }@b@ } else if (host.contains(":")) {@b@ int i = host.lastIndexOf(':');@b@ if (PNetUtils.isInvalidLocalHost(host.substring(0, i))) {@b@ return PNetUtils.getLocalHost() + host.substring(i);@b@ }@b@ } else {@b@ if (PNetUtils.isInvalidLocalHost(host)) {@b@ return PNetUtils.getLocalHost();@b@ }@b@ }@b@ return host;@b@ }@b@@b@ private static volatile InetAddress LOCAL_ADDRESS = null;@b@@b@ public static InetAddress getLocalAddress() {@b@ if (LOCAL_ADDRESS != null)@b@ return LOCAL_ADDRESS;@b@ InetAddress localAddress = getLocalAddress0();@b@ LOCAL_ADDRESS = localAddress;@b@ return localAddress;@b@ }@b@@b@ public static String getLogHost() {@b@ InetAddress address = LOCAL_ADDRESS;@b@ return address == null ? LOCALHOST : address.getHostAddress();@b@ }@b@@b@ public static boolean isValidLocalAddress(String ip) {@b@ InetAddress localAddress;@b@ try {@b@ localAddress = InetAddress.getByName(ip);@b@ } catch (UnknownHostException e) {@b@ return false;@b@ }@b@ return isValidLocalAddress(localAddress);@b@ }@b@@b@ public static boolean isValidLocalAddress(InetAddress localAddress) {@b@ if (!isValidAddress(localAddress)) {@b@ return false;@b@ }@b@@b@ try {@b@ InetAddress addr = InetAddress.getLocalHost();@b@ if (addr != null && addr.equals(localAddress)) {@b@ return true;@b@ }@b@ } catch (Throwable e) {@b@ logger.warn("Failed to retriving ip address, " + e.getMessage(), e);@b@ }@b@ try {@b@ Enumeration<NetworkInterface> interfaces = NetworkInterface@b@ .getNetworkInterfaces();@b@ if (interfaces != null) {@b@ while (interfaces.hasMoreElements()) {@b@ try {@b@ NetworkInterface network = interfaces.nextElement();@b@ Enumeration<InetAddress> addresses = network@b@ .getInetAddresses();@b@ if (addresses != null) {@b@ while (addresses.hasMoreElements()) {@b@ try {@b@ InetAddress address = addresses@b@ .nextElement();@b@ if (address != null@b@ && address.equals(localAddress)) {@b@ return true;@b@ }@b@ } catch (Throwable e) {@b@ logger.warn(@b@ "Failed to retriving ip address, "@b@ + e.getMessage(), e);@b@ }@b@ }@b@ }@b@ } catch (Throwable e) {@b@ logger.warn(@b@ "Failed to retriving ip address, "@b@ + e.getMessage(), e);@b@ }@b@ }@b@ }@b@ } catch (Throwable e) {@b@ logger.warn("Failed to retriving ip address, " + e.getMessage(), e);@b@ }@b@ return false;@b@ }@b@@b@ private static InetAddress getLocalAddress0() {@b@@b@ InetAddress localAddress = null;@b@ String instanceIp = InstanceSystemPropertyUtils.getInstanceIP();@b@ if (instanceIp != null && (instanceIp = instanceIp.trim()).length() > 0) {@b@ try {@b@ localAddress = InetAddress.getByName(instanceIp);@b@ if (isValidLocalAddress(localAddress)) {@b@ return localAddress;@b@ } else {@b@ throw new java.lang.IllegalArgumentException(@b@ "System property:instanceIp" + "=" + instanceIp@b@ + " error,not found in localAddresses.");@b@ }@b@ } catch (IllegalArgumentException ex) {@b@ throw ex;@b@ } catch (Throwable e) {@b@ throw new IllegalArgumentException(@b@ "System property:instanceIp=" + instanceIp@b@ + " error,cause:" + e.getMessage(), e);@b@ }@b@ }@b@ try {@b@ localAddress = InetAddress.getLocalHost();@b@ if (isValidAddress(localAddress)) {@b@ return localAddress;@b@ }@b@ } catch (Throwable e) {@b@ logger.warn("Failed to retriving ip address, " + e.getMessage(), e);@b@ }@b@ try {@b@ Enumeration<NetworkInterface> interfaces = NetworkInterface@b@ .getNetworkInterfaces();@b@ if (interfaces != null) {@b@ while (interfaces.hasMoreElements()) {@b@ try {@b@ NetworkInterface network = interfaces.nextElement();@b@ Enumeration<InetAddress> addresses = network@b@ .getInetAddresses();@b@ if (addresses != null) {@b@ while (addresses.hasMoreElements()) {@b@ try {@b@ InetAddress address = addresses@b@ .nextElement();@b@ if (isValidAddress(address)) {@b@ return address;@b@ }@b@ } catch (Throwable e) {@b@ logger.warn(@b@ "Failed to retriving ip address, "@b@ + e.getMessage(), e);@b@ }@b@ }@b@ }@b@ } catch (Throwable e) {@b@ logger.warn(@b@ "Failed to retriving ip address, "@b@ + e.getMessage(), e);@b@ }@b@ }@b@ }@b@ } catch (Throwable e) {@b@ logger.warn("Failed to retriving ip address, " + e.getMessage(), e);@b@ }@b@ logger.error("Could not get local host ip address, will use 127.0.0.1 instead.");@b@ return localAddress;@b@ }@b@@b@ private static final Map<String, String> hostNameCache = new LRUCache<String, String>(@b@ 16);@b@@b@ public static String getHostName(String address) {@b@ try {@b@ int i = address.indexOf(':');@b@ if (i > -1) {@b@ address = address.substring(0, i);@b@ }@b@ String hostname = hostNameCache.get(address);@b@ if (hostname != null && hostname.length() > 0) {@b@ return hostname;@b@ }@b@ InetAddress inetAddress = InetAddress.getByName(address);@b@ if (inetAddress != null) {@b@ hostname = inetAddress.getHostName();@b@ hostNameCache.put(address, hostname);@b@ return hostname;@b@ }@b@ } catch (Throwable e) {@b@ // ignore@b@ }@b@ return address;@b@ }@b@@b@ /**@b@ * @param hostName@b@ * @return ip address or hostName if UnknownHostException@b@ */@b@ public static String getIpByHost(String hostName) {@b@ try {@b@ return InetAddress.getByName(hostName).getHostAddress();@b@ } catch (UnknownHostException e) {@b@ return hostName;@b@ }@b@ }@b@@b@ public static String toAddressString(InetSocketAddress address) {@b@ return address.getAddress().getHostAddress() + ":" + address.getPort();@b@ }@b@@b@ public static InetSocketAddress toAddress(String address) {@b@ int i = address.indexOf(':');@b@ String host;@b@ int port;@b@ if (i > -1) {@b@ host = address.substring(0, i);@b@ port = Integer.parseInt(address.substring(i + 1));@b@ } else {@b@ host = address;@b@ port = 0;@b@ }@b@ return new InetSocketAddress(host, port);@b@ }@b@@b@ public static String toURL(String protocol, String host, int port,@b@ String path) {@b@ StringBuilder sb = new StringBuilder();@b@ sb.append(protocol).append("://");@b@ sb.append(host).append(':').append(port);@b@ if (path.charAt(0) != '/')@b@ sb.append('/');@b@ sb.append(path);@b@ return sb.toString();@b@ }@b@@b@}