You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by fe...@apache.org on 2011/04/04 16:59:14 UTC
svn commit: r1088657 [2/9] - in /james/server/trunk:
container-spring/src/main/java/org/apache/james/container/spring/bean/factory/mailrepositorystore/
core/src/main/java/org/apache/james/core/
data-api/src/main/java/org/apache/james/domainlist/api/ da...
Modified: james/server/trunk/data-library/src/main/java/org/apache/james/vut/lib/VirtualUserTableUtil.java
URL: http://svn.apache.org/viewvc/james/server/trunk/data-library/src/main/java/org/apache/james/vut/lib/VirtualUserTableUtil.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/data-library/src/main/java/org/apache/james/vut/lib/VirtualUserTableUtil.java (original)
+++ james/server/trunk/data-library/src/main/java/org/apache/james/vut/lib/VirtualUserTableUtil.java Mon Apr 4 14:59:11 2011
@@ -36,34 +36,40 @@ import org.apache.mailet.MailAddress;
*/
public class VirtualUserTableUtil {
- private VirtualUserTableUtil() {}
-
- // @deprecated QUERY is deprecated - SQL queries are now located in sqlResources.xml
+ private VirtualUserTableUtil() {
+ }
+
+ // @deprecated QUERY is deprecated - SQL queries are now located in
+ // sqlResources.xml
public static String QUERY = "select VirtualUserTable.target_address from VirtualUserTable, VirtualUserTable as VUTDomains where (VirtualUserTable.user like ? or VirtualUserTable.user like '\\%') and (VirtualUserTable.domain like ? or (VirtualUserTable.domain like '%*%' and VUTDomains.domain like ?)) order by concat(VirtualUserTable.user,'@',VirtualUserTable.domain) desc limit 1";
-
+
/**
* Processes regex virtual user mapping
- *
+ *
* If a mapped target string begins with the prefix regex:, it must be
- * formatted as regex:<regular-expression>:<parameterized-string>,
- * e.g., regex:(.*)@(.*):${1}@tld
- *
- * @param address the MailAddress to be mapped
- * @param targetString a String specifying the mapping
- * @throws MalformedPatternException
+ * formatted as regex:<regular-expression>:<parameterized-string>, e.g.,
+ * regex:(.*)@(.*):${1}@tld
+ *
+ * @param address
+ * the MailAddress to be mapped
+ * @param targetString
+ * a String specifying the mapping
+ * @throws MalformedPatternException
*/
- public static String regexMap( MailAddress address, String targetString) {
+ public static String regexMap(MailAddress address, String targetString) {
String result = null;
int identifierLength = VirtualUserTable.REGEX_PREFIX.length();
int msgPos = targetString.indexOf(':', identifierLength + 1);
// Throw exception on invalid format
- if (msgPos < identifierLength + 1) throw new PatternSyntaxException("Regex should be formatted as regex:<regular-expression>:<parameterized-string>", targetString, 0);
-
+ if (msgPos < identifierLength + 1)
+ throw new PatternSyntaxException("Regex should be formatted as regex:<regular-expression>:<parameterized-string>", targetString, 0);
+
// log("regex: targetString = " + targetString);
// log("regex: msgPos = " + msgPos);
- // log("regex: compile " + targetString.substring("regex:".length(), msgPos));
+ // log("regex: compile " + targetString.substring("regex:".length(),
+ // msgPos));
// log("regex: address = " + address.toString());
// log("regex: replace = " + targetString.substring(msgPos + 1));
@@ -76,16 +82,18 @@ public class VirtualUserTableUtil {
parameters.put(Integer.toString(i), match.group(i));
}
result = replaceParameters(targetString.substring(msgPos + 1), parameters);
- }
+ }
return result;
- }
+ }
/**
* Returns a named string, replacing parameters with the values set.
*
- * @param str the name of the String resource required.
- * @param parameters a map of parameters (name-value string pairs) which are
- * replaced where found in the input strings
+ * @param str
+ * the name of the String resource required.
+ * @param parameters
+ * a map of parameters (name-value string pairs) which are
+ * replaced where found in the input strings
* @return the requested resource
*/
static public String replaceParameters(String str, Map<String, String> parameters) {
@@ -93,28 +101,32 @@ public class VirtualUserTableUtil {
// Do parameter replacements for this string resource.
Iterator<String> paramNames = parameters.keySet().iterator();
StringBuffer replaceBuffer = new StringBuffer(64);
- while ( paramNames.hasNext() ) {
- String paramName = (String)paramNames.next();
- String paramValue = (String)parameters.get(paramName);
+ while (paramNames.hasNext()) {
+ String paramName = (String) paramNames.next();
+ String paramValue = (String) parameters.get(paramName);
replaceBuffer.append("${").append(paramName).append("}");
str = substituteSubString(str, replaceBuffer.toString(), paramValue);
- if (paramNames.hasNext()) replaceBuffer.setLength(0);
+ if (paramNames.hasNext())
+ replaceBuffer.setLength(0);
}
}
return str;
}
-
+
/**
- * Replace substrings of one string with another string and return altered string.
- * @param input input string
- * @param find the string to replace
- * @param replace the string to replace with
+ * Replace substrings of one string with another string and return altered
+ * string.
+ *
+ * @param input
+ * input string
+ * @param find
+ * the string to replace
+ * @param replace
+ * the string to replace with
* @return the substituted string
*/
- static private String substituteSubString( String input,
- String find,
- String replace ) {
+ static private String substituteSubString(String input, String find, String replace) {
int find_length = find.length();
int replace_length = replace.length();
@@ -122,7 +134,7 @@ public class VirtualUserTableUtil {
int index = input.indexOf(find);
int outputOffset = 0;
- while ( index > -1 ) {
+ while (index > -1) {
output.replace(index + outputOffset, index + outputOffset + find_length, replace);
outputOffset = outputOffset + (replace_length - find_length);
@@ -132,117 +144,121 @@ public class VirtualUserTableUtil {
String result = output.toString();
return result;
}
-
+
/**
* Returns the real recipient given a virtual username and domain.
*
- * @param user the virtual user
- * @param domain the virtual domain
- * @return the real recipient address, or <code>null</code> if no mapping exists
+ * @param user
+ * the virtual user
+ * @param domain
+ * the virtual domain
+ * @return the real recipient address, or <code>null</code> if no mapping
+ * exists
*/
public static String getTargetString(String user, String domain, Map<String, String> mappings) {
- StringBuffer buf;
- String target;
-
- //Look for exact (user@domain) match
- buf = new StringBuffer().append(user).append("@").append(domain);
- target = (String)mappings.get(buf.toString());
- if (target != null) {
- return target;
- }
-
- //Look for user@* match
- buf = new StringBuffer().append(user).append("@*");
- target = (String)mappings.get(buf.toString());
- if (target != null) {
- return target;
- }
-
- //Look for *@domain match
- buf = new StringBuffer().append("*@").append(domain);
- target = (String)mappings.get(buf.toString());
- if (target != null) {
- return target;
- }
-
- return null;
- }
-
- /**
- * Returns the character used to delineate multiple addresses.
- *
- * @param targetString the string to parse
- * @return the character to tokenize on
- */
- public static String getSeparator(String targetString) {
- return (targetString.indexOf(',') > -1 ? "," : (targetString
- .indexOf(';') > -1 ? ";" : ((targetString.indexOf(VirtualUserTable.ERROR_PREFIX) > -1
- || targetString.indexOf(VirtualUserTable.REGEX_PREFIX) > -1 || targetString.indexOf(VirtualUserTable.ALIASDOMAIN_PREFIX) > -1)? "" : ":")));
- }
-
- /**
- * Returns a Map which contains the mappings
- *
- * @param mapping A String which contains a list of mappings
- * @return Map which contains the mappings
- */
- public static Map<String, String> getXMLMappings(String mapping) {
- Map<String, String> mappings = new HashMap<String, String>();
- StringTokenizer tokenizer = new StringTokenizer(mapping, ",");
- while(tokenizer.hasMoreTokens()) {
- String mappingItem = tokenizer.nextToken();
- int index = mappingItem.indexOf('=');
- String virtual = mappingItem.substring(0, index).trim().toLowerCase();
- String real = mappingItem.substring(index + 1).trim().toLowerCase();
- mappings.put(virtual, real);
- }
- return mappings;
- }
-
-
+ StringBuffer buf;
+ String target;
+
+ // Look for exact (user@domain) match
+ buf = new StringBuffer().append(user).append("@").append(domain);
+ target = (String) mappings.get(buf.toString());
+ if (target != null) {
+ return target;
+ }
+
+ // Look for user@* match
+ buf = new StringBuffer().append(user).append("@*");
+ target = (String) mappings.get(buf.toString());
+ if (target != null) {
+ return target;
+ }
+
+ // Look for *@domain match
+ buf = new StringBuffer().append("*@").append(domain);
+ target = (String) mappings.get(buf.toString());
+ if (target != null) {
+ return target;
+ }
+
+ return null;
+ }
+
+ /**
+ * Returns the character used to delineate multiple addresses.
+ *
+ * @param targetString
+ * the string to parse
+ * @return the character to tokenize on
+ */
+ public static String getSeparator(String targetString) {
+ return (targetString.indexOf(',') > -1 ? "," : (targetString.indexOf(';') > -1 ? ";" : ((targetString.indexOf(VirtualUserTable.ERROR_PREFIX) > -1 || targetString.indexOf(VirtualUserTable.REGEX_PREFIX) > -1 || targetString.indexOf(VirtualUserTable.ALIASDOMAIN_PREFIX) > -1) ? "" : ":")));
+ }
+
+ /**
+ * Returns a Map which contains the mappings
+ *
+ * @param mapping
+ * A String which contains a list of mappings
+ * @return Map which contains the mappings
+ */
+ public static Map<String, String> getXMLMappings(String mapping) {
+ Map<String, String> mappings = new HashMap<String, String>();
+ StringTokenizer tokenizer = new StringTokenizer(mapping, ",");
+ while (tokenizer.hasMoreTokens()) {
+ String mappingItem = tokenizer.nextToken();
+ int index = mappingItem.indexOf('=');
+ String virtual = mappingItem.substring(0, index).trim().toLowerCase();
+ String real = mappingItem.substring(index + 1).trim().toLowerCase();
+ mappings.put(virtual, real);
+ }
+ return mappings;
+ }
+
/**
- * Return a Collection which holds the extracted mappings of the given String
+ * Return a Collection which holds the extracted mappings of the given
+ * String
*
* @param rawMapping
* @deprecated Use mappingToCollection(String rawMapping)
*/
- public static Collection<String> getMappings(String rawMapping) {
+ public static Collection<String> getMappings(String rawMapping) {
return mappingToCollection(rawMapping);
- }
-
- /**
- * Convert a raw mapping String to a Collection
- *
- * @param rawMapping the mapping String
- * @return map a collection which holds all mappings
- */
- public static ArrayList<String> mappingToCollection(String rawMapping) {
- ArrayList<String> map = new ArrayList<String>();
- StringTokenizer tokenizer = new StringTokenizer(rawMapping,
- VirtualUserTableUtil.getSeparator(rawMapping));
- while (tokenizer.hasMoreTokens()) {
- final String raw = tokenizer.nextToken().trim();
- map.add(raw);
- }
- return map;
- }
-
- /**
- * Convert a Collection which holds mappings to a raw mapping String
- *
- * @param map the Collection
- * @return mapping the mapping String
- */
- public static String CollectionToMapping(Collection<String> map) {
- StringBuffer mapping = new StringBuffer();
- Iterator<String> mappings = map.iterator();
- while (mappings.hasNext()) {
- mapping.append(mappings.next());
- if (mappings.hasNext()) {
- mapping.append(";");
- }
- }
- return mapping.toString();
}
-
+
+ /**
+ * Convert a raw mapping String to a Collection
+ *
+ * @param rawMapping
+ * the mapping String
+ * @return map a collection which holds all mappings
+ */
+ public static ArrayList<String> mappingToCollection(String rawMapping) {
+ ArrayList<String> map = new ArrayList<String>();
+ StringTokenizer tokenizer = new StringTokenizer(rawMapping, VirtualUserTableUtil.getSeparator(rawMapping));
+ while (tokenizer.hasMoreTokens()) {
+ final String raw = tokenizer.nextToken().trim();
+ map.add(raw);
+ }
+ return map;
+ }
+
+ /**
+ * Convert a Collection which holds mappings to a raw mapping String
+ *
+ * @param map
+ * the Collection
+ * @return mapping the mapping String
+ */
+ public static String CollectionToMapping(Collection<String> map) {
+ StringBuffer mapping = new StringBuffer();
+ Iterator<String> mappings = map.iterator();
+ while (mappings.hasNext()) {
+ mapping.append(mappings.next());
+ if (mappings.hasNext()) {
+ mapping.append(";");
+ }
+ }
+ return mapping.toString();
+ }
+
}
Modified: james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSService.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSService.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSService.java (original)
+++ james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSService.java Mon Apr 4 14:59:11 2011
@@ -22,72 +22,76 @@ import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
-
/**
- * Provides abstraction for DNS resolutions. The interface is Mail specific.
- * It may be a good idea to make the interface more generic or expose
- * commonly needed DNS methods.
+ * Provides abstraction for DNS resolutions. The interface is Mail specific. It
+ * may be a good idea to make the interface more generic or expose commonly
+ * needed DNS methods.
*/
public interface DNSService {
/**
- * <p>Return a prioritized unmodifiable list of host handling mail
- * for the domain.</p>
- *
- * <p>First lookup MX hosts, then MX hosts of the CNAME address, and
- * if no server is found return the IP of the hostname</p>
- *
- * @param hostname domain name to look up
- *
- * @return a unmodifiable list of handling servers corresponding to
- * this mail domain name
- * @throws TemporaryResolutionException get thrown on temporary problems
+ * <p>
+ * Return a prioritized unmodifiable list of host handling mail for the
+ * domain.
+ * </p>
+ *
+ * <p>
+ * First lookup MX hosts, then MX hosts of the CNAME address, and if no
+ * server is found return the IP of the hostname
+ * </p>
+ *
+ * @param hostname
+ * domain name to look up
+ *
+ * @return a unmodifiable list of handling servers corresponding to this
+ * mail domain name
+ * @throws TemporaryResolutionException
+ * get thrown on temporary problems
*/
Collection<String> findMXRecords(String hostname) throws TemporaryResolutionException;
/**
* Get a collection of DNS TXT Records
*
- * @param hostname The hostname to check
+ * @param hostname
+ * The hostname to check
* @return collection of strings representing TXT record values
*/
Collection<String> findTXTRecords(String hostname);
-
-
/**
- * Resolve the given hostname to an array of InetAddress based on the DNS Server.
- * It should not take into account the hostnames defined in the local
- * host table
+ * Resolve the given hostname to an array of InetAddress based on the DNS
+ * Server. It should not take into account the hostnames defined in the
+ * local host table
*
* @return An array of InetAddress
*/
InetAddress[] getAllByName(String host) throws UnknownHostException;
-
+
/**
- * Resolve the given hostname to an InetAddress based on the DNS Server.
- * It should not take into account the hostnames defined in the local
- * host table
+ * Resolve the given hostname to an InetAddress based on the DNS Server. It
+ * should not take into account the hostnames defined in the local host
+ * table
*
* @return The resolved InetAddress or null if not resolved
*/
InetAddress getByName(String host) throws UnknownHostException;
/**
- * Resolve the local hostname of the machine and returns it.
- * It relies on the hostname defined in the local host table
+ * Resolve the local hostname of the machine and returns it. It relies on
+ * the hostname defined in the local host table
*
* @return The local InetAddress of the machine.
*/
InetAddress getLocalHost() throws UnknownHostException;
/**
- * Resolve the given InetAddress to an host name based on the DNS Server.
- * It should not take into account the hostnames defined in the local
- * host table
+ * Resolve the given InetAddress to an host name based on the DNS Server. It
+ * should not take into account the hostnames defined in the local host
+ * table
*
* @return The resolved hostname String or null if not resolved
*/
String getHostName(InetAddress addr);
-
+
}
Modified: james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSServiceMBean.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSServiceMBean.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSServiceMBean.java (original)
+++ james/server/trunk/dnsservice-api/src/main/java/org/apache/james/dnsservice/api/DNSServiceMBean.java Mon Apr 4 14:59:11 2011
@@ -17,30 +17,27 @@
* under the License. *
****************************************************************/
-
-
package org.apache.james.dnsservice.api;
/**
* JMX MBean to manage the DNSService
- *
*/
public interface DNSServiceMBean {
- /**
- * Return the configured DNSServers
- *
- * @return servers
- */
+ /**
+ * Return the configured DNSServers
+ *
+ * @return servers
+ */
String[] getDNSServers();
-
+
/**
* Return the maximum cache size
*
* @return maxCacheSize
*/
int getMaximumCacheSize();
-
+
/**
* Return the current size of the cache
*
Modified: james/server/trunk/dnsservice-dnsjava/src/main/java/org/apache/james/dnsservice/dnsjava/DNSJavaService.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-dnsjava/src/main/java/org/apache/james/dnsservice/dnsjava/DNSJavaService.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-dnsjava/src/main/java/org/apache/james/dnsservice/dnsjava/DNSJavaService.java (original)
+++ james/server/trunk/dnsservice-dnsjava/src/main/java/org/apache/james/dnsservice/dnsjava/DNSJavaService.java Mon Apr 4 14:59:11 2011
@@ -56,39 +56,37 @@ import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
/**
- * Provides DNS client functionality to services running
- * inside James
+ * Provides DNS client functionality to services running inside James
*/
public class DNSJavaService implements DNSService, DNSServiceMBean, LogEnabled, Configurable {
/**
- * A resolver instance used to retrieve DNS records. This
- * is a reference to a third party library object.
+ * A resolver instance used to retrieve DNS records. This is a reference to
+ * a third party library object.
*/
protected Resolver resolver;
/**
- * A TTL cache of results received from the DNS server. This
- * is a reference to a third party library object.
+ * A TTL cache of results received from the DNS server. This is a reference
+ * to a third party library object.
*/
protected Cache cache;
/**
* Maximum number of RR to cache.
*/
-
private int maxCacheSize = 50000;
/**
* Whether the DNS response is required to be authoritative
*/
private int dnsCredibility;
-
+
/**
* The DNS servers to be used by this service
*/
private List<String> dnsServers = new ArrayList<String>();
-
+
/**
* The search paths to be used
*/
@@ -98,48 +96,49 @@ public class DNSJavaService implements D
* The MX Comparator used in the MX sort.
*/
private Comparator<MXRecord> mxComparator = new MXRecordComparator();
-
+
/**
- * If true register this service as the default resolver/cache for DNSJava static
- * calls
+ * If true register this service as the default resolver/cache for DNSJava
+ * static calls
*/
private boolean setAsDNSJavaDefault;
-
+
private String localHostName;
-
+
private String localCanonicalHostName;
-
+
private String localAddress;
-
-
+
private Logger logger;
-
-
+
/*
* (non-Javadoc)
+ *
* @see org.apache.james.lifecycle.LogEnabled#setLog(org.slf4j.Logger)
*/
public void setLog(Logger logger) {
this.logger = logger;
}
-
+
/*
* (non-Javadoc)
- * @see org.apache.james.lifecycle.Configurable#configure(org.apache.commons.configuration.HierarchicalConfiguration)
+ *
+ * @see
+ * org.apache.james.lifecycle.Configurable#configure(org.apache.commons.
+ * configuration.HierarchicalConfiguration)
*/
@SuppressWarnings("unchecked")
- public void configure(HierarchicalConfiguration configuration) throws ConfigurationException{
+ public void configure(HierarchicalConfiguration configuration) throws ConfigurationException {
- final boolean autodiscover =
- configuration.getBoolean( "autodiscover", true );
+ final boolean autodiscover = configuration.getBoolean("autodiscover", true);
List<Name> sPaths = new ArrayList<Name>();
if (autodiscover) {
logger.info("Autodiscovery is enabled - trying to discover your system's DNS Servers");
String[] serversArray = ResolverConfig.getCurrentConfig().servers();
if (serversArray != null) {
- for ( int i = 0; i < serversArray.length; i++ ) {
- dnsServers.add(serversArray[ i ]);
+ for (int i = 0; i < serversArray.length; i++) {
+ dnsServers.add(serversArray[i]);
logger.info("Adding autodiscovered server " + serversArray[i]);
}
}
@@ -155,29 +154,28 @@ public class DNSJavaService implements D
}
}
- //singleIPPerMX = configuration.getBoolean( "singleIPperMX", false );
+ // singleIPPerMX = configuration.getBoolean( "singleIPperMX", false );
+
+ setAsDNSJavaDefault = configuration.getBoolean("setAsDNSJavaDefault", true);
- setAsDNSJavaDefault = configuration.getBoolean( "setAsDNSJavaDefault" ,true );
-
// Get the DNS servers that this service will use for lookups
- final List<String> serversConfigurations = configuration.getList( "servers.server" );
-
+ final List<String> serversConfigurations = configuration.getList("servers.server");
- for ( int i = 0; i < serversConfigurations.size(); i++ ) {
- dnsServers.add( serversConfigurations.get(i) );
+ for (int i = 0; i < serversConfigurations.size(); i++) {
+ dnsServers.add(serversConfigurations.get(i));
}
// Get the DNS servers that this service will use for lookups
- final List<String> searchPathsConfiguration = configuration.getList( "searchpaths.searchpath" );
+ final List<String> searchPathsConfiguration = configuration.getList("searchpaths.searchpath");
- for ( int i = 0; i < searchPathsConfiguration.size(); i++ ) {
+ for (int i = 0; i < searchPathsConfiguration.size(); i++) {
try {
- sPaths.add( Name.fromString(searchPathsConfiguration.get(i)) );
+ sPaths.add(Name.fromString(searchPathsConfiguration.get(i)));
} catch (TextParseException e) {
- throw new ConfigurationException("Unable to parse searchpath host: "+searchPathsConfiguration.get(i),e);
+ throw new ConfigurationException("Unable to parse searchpath host: " + searchPathsConfiguration.get(i), e);
}
}
-
+
searchPaths = (Name[]) sPaths.toArray(new Name[0]);
if (dnsServers.isEmpty()) {
@@ -185,59 +183,55 @@ public class DNSJavaService implements D
dnsServers.add("127.0.0.1");
}
- final boolean authoritative =
- configuration.getBoolean( "authoritative" , false);
- // TODO: Check to see if the credibility field is being used correctly. From the
- // docs I don't think so
+ final boolean authoritative = configuration.getBoolean("authoritative", false);
+ // TODO: Check to see if the credibility field is being used correctly.
+ // From the
+ // docs I don't think so
dnsCredibility = authoritative ? Credibility.AUTH_ANSWER : Credibility.NONAUTH_ANSWER;
- maxCacheSize = configuration.getInt( "maxcachesize",maxCacheSize );
+ maxCacheSize = configuration.getInt("maxcachesize", maxCacheSize);
}
-
-
-
@PostConstruct
- public void init()
- throws Exception {
- logger.debug("DNSService init...");
+ public void init() throws Exception {
+ logger.debug("DNSService init...");
// If no DNS servers were configured, default to local host
if (dnsServers.isEmpty()) {
try {
- dnsServers.add( InetAddress.getLocalHost().getHostName() );
- } catch ( UnknownHostException ue ) {
- dnsServers.add( "127.0.0.1" );
+ dnsServers.add(InetAddress.getLocalHost().getHostName());
+ } catch (UnknownHostException ue) {
+ dnsServers.add("127.0.0.1");
}
}
- //Create the extended resolver...
- final String[] serversArray = (String[])dnsServers.toArray(new String[0]);
+ // Create the extended resolver...
+ final String[] serversArray = (String[]) dnsServers.toArray(new String[0]);
if (logger.isInfoEnabled()) {
- for(int c = 0; c < serversArray.length; c++) {
+ for (int c = 0; c < serversArray.length; c++) {
logger.info("DNS Server is: " + serversArray[c]);
}
}
try {
- resolver = new ExtendedResolver( serversArray );
+ resolver = new ExtendedResolver(serversArray);
} catch (UnknownHostException uhe) {
logger.error("DNS service could not be initialized. The DNS servers specified are not recognized hosts.", uhe);
throw uhe;
}
- cache = new Cache (DClass.IN);
+ cache = new Cache(DClass.IN);
cache.setMaxEntries(maxCacheSize);
-
+
if (setAsDNSJavaDefault) {
Lookup.setDefaultResolver(resolver);
Lookup.setDefaultCache(cache, DClass.IN);
Lookup.setDefaultSearchPath(searchPaths);
logger.info("Registered cache, resolver and search paths as DNSJava defaults");
}
-
- // Cache the local hostname and local address. This is needed because
+
+ // Cache the local hostname and local address. This is needed because
// the following issues:
// JAMES-787
// JAMES-302
@@ -245,37 +239,38 @@ public class DNSJavaService implements D
localCanonicalHostName = addr.getCanonicalHostName();
localHostName = addr.getHostName();
localAddress = addr.getHostAddress();
-
+
logger.debug("DNSService ...init end");
}
/**
- * <p>Return the list of DNS servers in use by this service</p>
- *
+ * Return the list of DNS servers in use by this service
+ *
* @return an array of DNS server names
*/
public String[] getDNSServers() {
- return (String[])dnsServers.toArray(new String[0]);
+ return (String[]) dnsServers.toArray(new String[0]);
}
/**
- * <p>Return the list of DNS servers in use by this service</p>
- *
+ * Return the list of DNS servers in use by this service
+ *
* @return an array of DNS server names
*/
public Name[] getSearchPaths() {
return searchPaths;
}
-
/**
- * <p>Return a prioritized unmodifiable list of MX records
- * obtained from the server.</p>
- *
- * @param hostname domain name to look up
- *
+ * Return a prioritized unmodifiable list of MX records obtained from the
+ * server.
+ *
+ * @param hostname
+ * domain name to look up
+ *
* @return a list of MX records corresponding to this mail domain
- * @throws TemporaryResolutionException get thrown on temporary problems
+ * @throws TemporaryResolutionException
+ * get thrown on temporary problems
*/
private List<String> findMXRecordsRaw(String hostname) throws TemporaryResolutionException {
Record answers[] = lookup(hostname, Type.MX, "MX");
@@ -285,11 +280,12 @@ public class DNSJavaService implements D
}
MXRecord[] mxAnswers = new MXRecord[answers.length];
-
+
for (int i = 0; i < answers.length; i++) {
mxAnswers[i] = (MXRecord) answers[i];
}
- // just sort for now.. This will ensure that mx records with same prio are in sequence
+ // just sort for now.. This will ensure that mx records with same prio
+ // are in sequence
Arrays.sort(mxAnswers, mxComparator);
// now add the mx records to the right list and take care of shuffle
@@ -311,22 +307,22 @@ public class DNSJavaService implements D
}
}
// see if we need to insert the elements now
- if (same == false || i +1 == mxAnswers.length) {
+ if (same == false || i + 1 == mxAnswers.length) {
// shuffle entries with same prio
- // JAMES-913
+ // JAMES-913
Collections.shuffle(samePrio);
servers.addAll(samePrio);
-
- if (same == false && i +1 < mxAnswers.length) {
+
+ if (same == false && i + 1 < mxAnswers.length) {
samePrio.clear();
samePrio.add(mx.getTarget().toString());
}
}
- logger.debug(new StringBuffer("Found MX record ").append(mx.getTarget ().toString ()).toString());
+ logger.debug(new StringBuffer("Found MX record ").append(mx.getTarget().toString()).toString());
}
return servers;
}
-
+
/**
* @see org.apache.james.dnsservice.api.DNSService#findMXRecords(String)
*/
@@ -336,26 +332,19 @@ public class DNSJavaService implements D
servers = findMXRecordsRaw(hostname);
return Collections.unmodifiableCollection(servers);
} finally {
- //If we found no results, we'll add the original domain name if
- //it's a valid DNS entry
- if (servers.size () == 0) {
- StringBuffer logBuffer =
- new StringBuffer(128)
- .append("Couldn't resolve MX records for domain ")
- .append(hostname)
- .append(".");
+ // If we found no results, we'll add the original domain name if
+ // it's a valid DNS entry
+ if (servers.size() == 0) {
+ StringBuffer logBuffer = new StringBuffer(128).append("Couldn't resolve MX records for domain ").append(hostname).append(".");
logger.info(logBuffer.toString());
try {
getByName(hostname);
servers.add(hostname);
} catch (UnknownHostException uhe) {
// The original domain name is not a valid host,
- // so we can't add it to the server list. In this
+ // so we can't add it to the server list. In this
// case we return an empty list of servers
- logBuffer = new StringBuffer(128)
- .append("Couldn't resolve IP address for host ")
- .append(hostname)
- .append(".");
+ logBuffer = new StringBuffer(128).append("Couldn't resolve IP address for host ").append(hostname).append(".");
logger.error(logBuffer.toString());
}
}
@@ -364,41 +353,41 @@ public class DNSJavaService implements D
/**
* Looks up DNS records of the specified type for the specified name.
- *
- * This method is a public wrapper for the private implementation
- * method
- *
- * @param namestr the name of the host to be looked up
- * @param type the type of record desired
- * @param typeDesc the description of the record type, for debugging purpose
+ *
+ * This method is a public wrapper for the private implementation method
+ *
+ * @param namestr
+ * the name of the host to be looked up
+ * @param type
+ * the type of record desired
+ * @param typeDesc
+ * the description of the record type, for debugging purpose
*/
protected Record[] lookup(String namestr, int type, String typeDesc) throws TemporaryResolutionException {
// Name name = null;
try {
// name = Name.fromString(namestr, Name.root);
Lookup l = new Lookup(namestr, type);
-
+
l.setCache(cache);
l.setResolver(resolver);
l.setCredibility(dnsCredibility);
l.setSearchPath(searchPaths);
Record[] r = l.run();
-
+
try {
if (l.getResult() == Lookup.TRY_AGAIN) {
- throw new TemporaryResolutionException(
- "DNSService is temporary not reachable");
+ throw new TemporaryResolutionException("DNSService is temporary not reachable");
} else {
return r;
}
} catch (IllegalStateException ise) {
// This is okay, because it mimics the original behaviour
- // TODO find out if it's a bug in DNSJava
+ // TODO find out if it's a bug in DNSJava
logger.debug("Error determining result ", ise);
- throw new TemporaryResolutionException(
- "DNSService is temporary not reachable");
+ throw new TemporaryResolutionException("DNSService is temporary not reachable");
}
-
+
// return rawDNSLookup(name, false, type, typeDesc);
} catch (TextParseException tpe) {
// TODO: Figure out how to handle this correctly.
@@ -406,7 +395,7 @@ public class DNSJavaService implements D
return null;
}
}
-
+
protected Record[] lookupNoException(String namestr, int type, String typeDesc) {
try {
return lookup(namestr, type, typeDesc);
@@ -414,40 +403,37 @@ public class DNSJavaService implements D
return null;
}
}
-
- /* RFC 2821 section 5 requires that we sort the MX records by their
- * preference.
- * Reminder for maintainers: the return value on a Comparator can
- * be counter-intuitive for those who aren't used to the old C
- * strcmp function:
- *
- * < 0 ==> a < b
- * = 0 ==> a = b
- * > 0 ==> a > b
+
+ /*
+ * RFC 2821 section 5 requires that we sort the MX records by their
+ * preference. Reminder for maintainers: the return value on a Comparator
+ * can be counter-intuitive for those who aren't used to the old C strcmp
+ * function:
+ *
+ * < 0 ==> a < b = 0 ==> a = b > 0 ==> a > b
*/
private static class MXRecordComparator implements Comparator<MXRecord> {
- public int compare (MXRecord a, MXRecord b) {
+ public int compare(MXRecord a, MXRecord b) {
int pa = a.getPriority();
int pb = b.getPriority();
return pa - pb;
}
}
-
- /* java.net.InetAddress.get[All]ByName(String) allows an IP literal
- * to be passed, and will recognize it even with a trailing '.'.
- * However, org.xbill.DNS.Address does not recognize an IP literal
- * with a trailing '.' character. The problem is that when we
- * lookup an MX record for some domains, we may find an IP address,
- * which will have had the trailing '.' appended by the time we get
- * it back from dnsjava. An MX record is not allowed to have an IP
- * address as the right-hand-side, but there are still plenty of
- * such records on the Internet. Since java.net.InetAddress can
+ /*
+ * java.net.InetAddress.get[All]ByName(String) allows an IP literal to be
+ * passed, and will recognize it even with a trailing '.'. However,
+ * org.xbill.DNS.Address does not recognize an IP literal with a trailing
+ * '.' character. The problem is that when we lookup an MX record for some
+ * domains, we may find an IP address, which will have had the trailing '.'
+ * appended by the time we get it back from dnsjava. An MX record is not
+ * allowed to have an IP address as the right-hand-side, but there are still
+ * plenty of such records on the Internet. Since java.net.InetAddress can
* handle them, for the time being we've decided to support them.
- *
- * These methods are NOT intended for use outside of James, and are
- * NOT declared by the org.apache.james.services.DNSServer. This is
- * currently a stopgap measure to be revisited for the next release.
+ *
+ * These methods are NOT intended for use outside of James, and are NOT
+ * declared by the org.apache.james.services.DNSServer. This is currently a
+ * stopgap measure to be revisited for the next release.
*/
private static String allowIPLiteral(String host) {
@@ -465,13 +451,13 @@ public class DNSJavaService implements D
*/
public InetAddress getByName(String host) throws UnknownHostException {
String name = allowIPLiteral(host);
-
+
try {
// Check if its local
- if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) ||name.equals(localAddress)) {
+ if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) {
return getLocalHost();
}
-
+
return org.xbill.DNS.Address.getByAddress(name);
} catch (UnknownHostException e) {
Record[] records = lookupNoException(name, Type.A, "A");
@@ -479,7 +465,8 @@ public class DNSJavaService implements D
if (records != null && records.length >= 1) {
ARecord a = (ARecord) records[0];
return InetAddress.getByAddress(name, a.getAddress().getAddress());
- } else throw e;
+ } else
+ throw e;
}
}
@@ -490,39 +477,40 @@ public class DNSJavaService implements D
String name = allowIPLiteral(host);
try {
// Check if its local
- if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) ||name.equals(localAddress)) {
- return new InetAddress[] {getLocalHost()};
+ if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) {
+ return new InetAddress[] { getLocalHost() };
}
-
+
InetAddress addr = org.xbill.DNS.Address.getByAddress(name);
- return new InetAddress[] {addr};
+ return new InetAddress[] { addr };
} catch (UnknownHostException e) {
Record[] records = lookupNoException(name, Type.A, "A");
-
+
if (records != null && records.length >= 1) {
- InetAddress [] addrs = new InetAddress[records.length];
+ InetAddress[] addrs = new InetAddress[records.length];
for (int i = 0; i < records.length; i++) {
ARecord a = (ARecord) records[i];
addrs[i] = InetAddress.getByAddress(name, a.getAddress().getAddress());
}
return addrs;
- } else throw e;
+ } else
+ throw e;
}
}
-
+
/**
* @see org.apache.james.dnsservice.api.DNSService#findTXTRecords(String)
*/
- public Collection<String> findTXTRecords(String hostname){
+ public Collection<String> findTXTRecords(String hostname) {
List<String> txtR = new ArrayList<String>();
Record[] records = lookupNoException(hostname, Type.TXT, "TXT");
-
+
if (records != null) {
- for (int i = 0; i < records.length; i++) {
- TXTRecord txt = (TXTRecord) records[i];
- txtR.add(txt.rdataToString());
- }
-
+ for (int i = 0; i < records.length; i++) {
+ TXTRecord txt = (TXTRecord) records[i];
+ txtR.add(txt.rdataToString());
+ }
+
}
return txtR;
}
@@ -530,7 +518,7 @@ public class DNSJavaService implements D
/**
* @see org.apache.james.dnsservice.api.DNSService#getHostName(java.net.InetAddress)
*/
- public String getHostName(InetAddress addr){
+ public String getHostName(InetAddress addr) {
String result = null;
Name name = ReverseMap.fromAddress(addr);
Record[] records = lookupNoException(name.toString(), Type.PTR, "PTR");
Modified: james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/MXHostAddressIterator.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/MXHostAddressIterator.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/MXHostAddressIterator.java (original)
+++ james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/MXHostAddressIterator.java Mon Apr 4 14:59:11 2011
@@ -30,9 +30,8 @@ import org.slf4j.Logger;
*
*
*/
-public class MXHostAddressIterator implements Iterator<HostAddress>{
+public class MXHostAddressIterator implements Iterator<HostAddress> {
-
private Iterator<HostAddress> addresses = null;
private Iterator<String> hosts;
private DNSService dns;
@@ -43,7 +42,6 @@ public class MXHostAddressIterator imple
public MXHostAddressIterator(Iterator<String> hosts, DNSService dns, boolean useSingleIP, Logger logger) {
this(hosts, 25, dns, useSingleIP, logger);
}
-
public MXHostAddressIterator(Iterator<String> hosts, int defaultPort, DNSService dns, boolean useSingleIP, Logger logger) {
this.hosts = hosts;
@@ -52,75 +50,73 @@ public class MXHostAddressIterator imple
this.logger = logger;
this.defaultPort = defaultPort;
}
-
+
/*
* (non-Javadoc)
+ *
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
- /* Make sure that when next() is called, that we can
- * provide a HostAddress. This means that we need to
- * have an inner iterator, and verify that it has
- * addresses. We could, for example, run into a
- * situation where the next mxHost didn't have any valid
- * addresses.
+ /*
+ * Make sure that when next() is called, that we can provide a
+ * HostAddress. This means that we need to have an inner iterator, and
+ * verify that it has addresses. We could, for example, run into a
+ * situation where the next mxHost didn't have any valid addresses.
*/
- if ((addresses == null || !addresses.hasNext()) && hosts.hasNext()) do {
- String nextHostname = (String)hosts.next();
- final String hostname;
- final String port;
-
-
- int idx = nextHostname.indexOf(':');
- if ( idx > 0) {
- port = nextHostname.substring(idx+1);
- hostname = nextHostname.substring(0,idx);
- } else {
- hostname = nextHostname;
- port = defaultPort + "";
- }
-
- InetAddress[] addrs = null;
- try {
- if (useSingleIP) {
- addrs = new InetAddress[] {dns.getByName(hostname)};
+ if ((addresses == null || !addresses.hasNext()) && hosts.hasNext())
+ do {
+ String nextHostname = (String) hosts.next();
+ final String hostname;
+ final String port;
+
+ int idx = nextHostname.indexOf(':');
+ if (idx > 0) {
+ port = nextHostname.substring(idx + 1);
+ hostname = nextHostname.substring(0, idx);
} else {
- addrs = dns.getAllByName(hostname);
+ hostname = nextHostname;
+ port = defaultPort + "";
}
- } catch (UnknownHostException uhe) {
- // this should never happen, since we just got
- // this host from mxHosts, which should have
- // already done this check.
- StringBuffer logBuffer = new StringBuffer(128)
- .append("Couldn't resolve IP address for discovered host ")
- .append(hostname)
- .append(".");
- logger.error(logBuffer.toString());
- }
- final InetAddress[] ipAddresses = addrs;
-
- addresses = new Iterator<HostAddress>() {
- int i = 0;
- public boolean hasNext() {
- return ipAddresses != null && i < ipAddresses.length;
+ InetAddress[] addrs = null;
+ try {
+ if (useSingleIP) {
+ addrs = new InetAddress[] { dns.getByName(hostname) };
+ } else {
+ addrs = dns.getAllByName(hostname);
+ }
+ } catch (UnknownHostException uhe) {
+ // this should never happen, since we just got
+ // this host from mxHosts, which should have
+ // already done this check.
+ StringBuffer logBuffer = new StringBuffer(128).append("Couldn't resolve IP address for discovered host ").append(hostname).append(".");
+ logger.error(logBuffer.toString());
}
+ final InetAddress[] ipAddresses = addrs;
- public HostAddress next() {
- return new org.apache.mailet.HostAddress(hostname, "smtp://" + ipAddresses[i++].getHostAddress() +":" + port);
- }
+ addresses = new Iterator<HostAddress>() {
+ int i = 0;
- public void remove() {
- throw new UnsupportedOperationException ("remove not supported by this iterator");
- }
- };
- } while (!addresses.hasNext() && hosts.hasNext());
+ public boolean hasNext() {
+ return ipAddresses != null && i < ipAddresses.length;
+ }
+
+ public HostAddress next() {
+ return new org.apache.mailet.HostAddress(hostname, "smtp://" + ipAddresses[i++].getHostAddress() + ":" + port);
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException("remove not supported by this iterator");
+ }
+ };
+ } while (!addresses.hasNext() && hosts.hasNext());
return addresses != null && addresses.hasNext();
}
/*
* (non-Javadoc)
+ *
* @see java.util.Iterator#next()
*/
public HostAddress next() {
@@ -128,10 +124,10 @@ public class MXHostAddressIterator imple
}
/**
- * Not supported.
+ * Not supported.
*/
public void remove() {
- throw new UnsupportedOperationException ("remove not supported by this iterator");
+ throw new UnsupportedOperationException("remove not supported by this iterator");
}
}
Modified: james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/InetNetworkBuilder.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/InetNetworkBuilder.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/InetNetworkBuilder.java (original)
+++ james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/InetNetworkBuilder.java Mon Apr 4 14:59:11 2011
@@ -26,11 +26,16 @@ import org.apache.james.dnsservice.libra
import org.apache.james.dnsservice.library.inetnetwork.model.InetNetwork;
/**
- * Builds a InetNetwork (Inet4Network or Inet6Network) in function
- * on the provided string pattern that represents a subnet.
+ * <p>
+ * Builds a InetNetwork (Inet4Network or Inet6Network) in function on the
+ * provided string pattern that represents a subnet.
+ * </p>
*
- * Inet4Network is constructed based on the IPv4
- * subnet expressed in one of several formats:
+ * <p>
+ * Inet4Network is constructed based on the IPv4 subnet expressed in one of
+ * several formats:
+ *
+ * <pre>
* IPv4 Format Example
* Explicit address 127.0.0.1
* Address with a wildcard 127.0.0.*
@@ -39,10 +44,16 @@ import org.apache.james.dnsservice.libra
* Domain name + mask myHost.com/255.255.255.0
* IP address + prefix-length 127.0.0.0/8
* IP + mask 127.0.0.0/255.0.0.0
+ * </pre>
+ *
* For more information on IP V4, see RFC 1518 and RFC 1519.
- *
- * Inet6Network is constructed based on the IPv4
- * subnet expressed in one of several formats:
+ * </p>
+ *
+ * <p>
+ * Inet6Network is constructed based on the IPv4 subnet expressed in one of
+ * several formats:
+ *
+ * <pre>
* IPv6 Format Example
* Explicit address 0000:0000:0000:0000:0000:0000:0000:0001
* IP address + subnet mask (/) 0000:0000:0000:0000:0000:0000:0000:0001/64
@@ -52,32 +63,37 @@ import org.apache.james.dnsservice.libra
* Domain name + mask (/) myHost.com/48
* Domain name + mask (%) myHost.com%48
* Explicit shorted address ::1
- * For more information on IP V6, see RFC 2460. (see also http://en.wikipedia.org/wiki/IPv6_address)
+ * </pre>
+ *
+ * For more information on IP V6, see RFC 2460. (See also <a
+ * href="http://en.wikipedia.org/wiki/IPv6_address"
+ * >http://en.wikipedia.org/wiki/IPv6_address</a>)
+ * </p>
*/
public class InetNetworkBuilder {
/**
- * The DNS Server used to create InetAddress for
- * hostnames and IP adresses.
+ * The DNS Server used to create InetAddress for hostnames and IP adresses.
*/
private DNSService dnsService;
/**
* Constructs a InetNetwork.
*
- * @param dnsServer the DNSService to use
+ * @param dnsServer
+ * the DNSService to use
*/
public InetNetworkBuilder(DNSService dnsServer) {
this.dnsService = dnsServer;
}
/**
- * Creates a InetNetwork for the given String.
- * Depending on the provided pattern and the platform configuration
- * (IPv4 and/or IPv6), the returned type will be Inet4Network
- * or Inet6Network.
+ * Creates a InetNetwork for the given String. Depending on the provided
+ * pattern and the platform configuration (IPv4 and/or IPv6), the returned
+ * type will be Inet4Network or Inet6Network.
*
- * @param netspec the String which is will converted to InetNetwork
+ * @param netspec
+ * the String which is will converted to InetNetwork
* @return network the InetNetwork
* @throws java.net.UnknownHostException
*/
@@ -86,8 +102,9 @@ public class InetNetworkBuilder {
}
/**
- * Returns true if the string parameters is a IPv6 pattern.
- * Currently, only tests for presence of ':'.
+ * Returns true if the string parameters is a IPv6 pattern. Currently, only
+ * tests for presence of ':'.
+ *
* @param address
* @return boolean
*/
@@ -98,78 +115,73 @@ public class InetNetworkBuilder {
/**
* Get a Inet4Network for the given String.
*
- * @param netspec the String which is will converted to InetNetwork
+ * @param netspec
+ * the String which is will converted to InetNetwork
* @return network the InetNetwork
* @throws java.net.UnknownHostException
*/
private InetNetwork getV4FromString(String netspec) throws UnknownHostException {
-
+
if (netspec.endsWith("*")) {
netspec = normalizeV4FromAsterisk(netspec);
- }
- else {
+ } else {
int iSlash = netspec.indexOf('/');
if (iSlash == -1) {
netspec += "/255.255.255.255";
- }
- else if (netspec.indexOf('.', iSlash) == -1) {
+ } else if (netspec.indexOf('.', iSlash) == -1) {
netspec = normalizeV4FromCIDR(netspec);
}
}
- return new Inet4Network(
- dnsService.getByName(netspec.substring(0, netspec.indexOf('/'))),
- dnsService.getByName(netspec.substring(netspec.indexOf('/') + 1)));
+ return new Inet4Network(dnsService.getByName(netspec.substring(0, netspec.indexOf('/'))), dnsService.getByName(netspec.substring(netspec.indexOf('/') + 1)));
}
/**
* Get a Inet6Network for the given String.
*
- * @param netspec the String which is will converted to InetNetwork
+ * @param netspec
+ * the String which is will converted to InetNetwork
* @return network the InetNetwork
* @throws java.net.UnknownHostException
*/
private InetNetwork getV6FromString(String netspec) throws UnknownHostException {
-
+
if (netspec.endsWith("*")) {
throw new UnsupportedOperationException("Wildcard for IPv6 not supported");
}
-
+
// Netmask can be separated with %
netspec = netspec.replaceAll("%", "/");
-
+
if (netspec.indexOf('/') == -1) {
netspec += "/32768";
}
- return new Inet6Network(
- dnsService.getByName(netspec.substring(0, netspec.indexOf('/'))),
- new Integer(netspec.substring(netspec.indexOf('/') + 1)));
+ return new Inet6Network(dnsService.getByName(netspec.substring(0, netspec.indexOf('/'))), new Integer(netspec.substring(netspec.indexOf('/') + 1)));
}
/**
* This converts from an uncommon "wildcard" CIDR format to "address + mask"
* format:
+ *
+ * <pre>
* * => 000.000.000.0/000.000.000.0
* xxx.* => xxx.000.000.0/255.000.000.0
* xxx.xxx.* => xxx.xxx.000.0/255.255.000.0
* xxx.xxx.xxx.* => xxx.xxx.xxx.0/255.255.255.0
+ * </pre>
*
* @param netspec
* @return addrMask the address/mask of the given argument
*/
private static String normalizeV4FromAsterisk(final String netspec) {
- String[] masks = {
- "0.0.0.0/0.0.0.0",
- "0.0.0/255.0.0.0",
- "0.0/255.255.0.0",
- "0/255.255.255.0" };
-
+ String[] masks = { "0.0.0.0/0.0.0.0", "0.0.0/255.0.0.0", "0.0/255.255.0.0", "0/255.255.255.0" };
+
char[] srcb = netspec.toCharArray();
-
+
int octets = 0;
-
+
for (int i = 1; i < netspec.length(); i++) {
if (srcb[i] == '.')
octets++;
@@ -182,9 +194,21 @@ public class InetNetworkBuilder {
/**
* RFC 1518, 1519 - Classless Inter-Domain Routing (CIDR) This converts from
* "prefix + prefix-length" format to "address + mask" format, e.g. from
- * xxx.xxx.xxx.xxx/yy to xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy.
*
- * @param netspec the xxx.xxx.xxx.xxx/yyy format
+ * <pre>
+ * xxx.xxx.xxx.xxx / yy
+ * </pre>
+ *
+ * to
+ *
+ * <pre>
+ * xxx.xxx.xxx.xxx / yyy.yyy.yyy.yyy
+ * </pre>
+ *
+ * .
+ *
+ * @param netspec
+ * the xxx.xxx.xxx.xxx/yyy format
* @return addrMask the xxx.xxx.xxx.xxx/yyy.yyy.yyy.yyy format
*/
private static String normalizeV4FromCIDR(final String netspec) {
@@ -193,12 +217,8 @@ public class InetNetworkBuilder {
final int mask = (bits == 32) ? 0 : 0xFFFFFFFF - ((1 << bits) - 1);
- return netspec.substring(0, netspec.indexOf('/') + 1)
- + Integer.toString(mask >> 24 & 0xFF, 10) + "."
- + Integer.toString(mask >> 16 & 0xFF, 10) + "."
- + Integer.toString(mask >> 8 & 0xFF, 10) + "."
- + Integer.toString(mask >> 0 & 0xFF, 10);
-
+ return netspec.substring(0, netspec.indexOf('/') + 1) + Integer.toString(mask >> 24 & 0xFF, 10) + "." + Integer.toString(mask >> 16 & 0xFF, 10) + "." + Integer.toString(mask >> 8 & 0xFF, 10) + "." + Integer.toString(mask >> 0 & 0xFF, 10);
+
}
-
+
}
Modified: james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet4Network.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet4Network.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet4Network.java (original)
+++ james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet4Network.java Mon Apr 4 14:59:11 2011
@@ -39,21 +39,26 @@ public class Inet4Network implements Ine
* The subnet mask to apply on the IP address.
*/
private InetAddress netmask;
-
+
/**
- * You need a IP address and an subnetmask to construct an Inet4Network.<br/>
+ * You need a IP address and an subnetmask to construct an Inet4Network.<br>
* Both constructor parameters are passed via a InetAddress.
*
- * @param ip the InetAddress to init the class
- * @param netmask the InetAddress represent the netmask to init the class
+ * @param ip
+ * the InetAddress to init the class
+ * @param netmask
+ * the InetAddress represent the netmask to init the class
*/
public Inet4Network(InetAddress ip, InetAddress netmask) {
network = maskIP(ip, netmask);
this.netmask = netmask;
}
- /* (non-Javadoc)
- * @see org.apache.james.api.dnsservice.model.InetNetwork#contains(java.net.InetAddress)
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.james.api.dnsservice.model.InetNetwork#contains(java.net.
+ * InetAddress)
*/
public boolean contains(final InetAddress ip) {
if (InetNetworkBuilder.isV6(ip.getHostAddress())) {
@@ -61,34 +66,38 @@ public class Inet4Network implements Ine
}
try {
return network.equals(maskIP(ip, netmask));
- }
- catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
return false;
}
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#toString()
*/
public String toString() {
return network.getHostAddress() + "/" + netmask.getHostAddress();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return maskIP(network, netmask).hashCode();
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
- return (obj != null)
- && (obj instanceof InetNetwork)
- && ((((Inet4Network) obj).network.equals(network)) && (((Inet4Network) obj).netmask.equals(netmask)));
+ return (obj != null) && (obj instanceof InetNetwork) && ((((Inet4Network) obj).network.equals(network)) && (((Inet4Network) obj).netmask.equals(netmask)));
}
+
/**
* @see #maskIP(byte[], byte[])
*/
@@ -97,11 +106,13 @@ public class Inet4Network implements Ine
}
/**
- * Return InetAddress generated of the passed arguments.
- * Return Null if any error occurs
+ * Return InetAddress generated of the passed arguments. Return Null if any
+ * error occurs
*
- * @param ip the byte[] represent the ip
- * @param mask the byte[] represent the netmask
+ * @param ip
+ * the byte[] represent the ip
+ * @param mask
+ * the byte[] represent the netmask
* @return inetAddress the InetAddress generated of the passed arguments.
*/
private static InetAddress maskIP(final byte[] ip, final byte[] mask) {
@@ -113,7 +124,7 @@ public class Inet4Network implements Ine
}
try {
byte[] maskedIp = new byte[ip.length];
- for (int i=0; i < ip.length; i++) {
+ for (int i = 0; i < ip.length; i++) {
maskedIp[i] = (byte) (ip[i] & mask[i]);
}
return getByAddress(maskedIp);
@@ -125,26 +136,23 @@ public class Inet4Network implements Ine
/**
* Return InetAddress which represent the given byte[]
*
- * @param ip the byte[] represent the ip
+ * @param ip
+ * the byte[] represent the ip
* @return ip the InetAddress generated of the given byte[]
* @throws java.net.UnknownHostException
*/
private static InetAddress getByAddress(byte[] ip) throws UnknownHostException {
InetAddress addr = null;
-
+
addr = Inet4Address.getByAddress(ip);
if (addr == null) {
- addr = InetAddress.getByName(
- Integer.toString(ip[0] & 0xFF, 10) + "."
- + Integer.toString(ip[1] & 0xFF, 10) + "."
- + Integer.toString(ip[2] & 0xFF, 10) + "."
- + Integer.toString(ip[3] & 0xFF, 10));
+ addr = InetAddress.getByName(Integer.toString(ip[0] & 0xFF, 10) + "." + Integer.toString(ip[1] & 0xFF, 10) + "." + Integer.toString(ip[2] & 0xFF, 10) + "." + Integer.toString(ip[3] & 0xFF, 10));
}
-
+
return addr;
-
+
}
}
Modified: james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet6Network.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet6Network.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet6Network.java (original)
+++ james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/Inet6Network.java Mon Apr 4 14:59:11 2011
@@ -39,29 +39,34 @@ public class Inet6Network implements Ine
* The subnet mask to apply on the IP address.
*/
private Integer netmask;
-
+
/**
- * You need a IP address (InetAddress) and an subnetmask (Integer) to construct an Inet6Network.<br/>
+ * You need a IP address (InetAddress) and an subnetmask (Integer) to
+ * construct an Inet6Network.
*
- * @param ip the InetAddress to init the class
- * @param netmask the InetAddress represent the netmask to init the class
+ * @param ip
+ * the InetAddress to init the class
+ * @param netmask
+ * the InetAddress represent the netmask to init the class
*/
public Inet6Network(InetAddress ip, Integer netmask) {
network = maskIP(ip, netmask);
this.netmask = netmask;
}
- /* (non-Javadoc)
- * @see org.apache.james.api.dnsservice.model.InetNetwork#contains(java.net.InetAddress)
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.james.api.dnsservice.model.InetNetwork#contains(java.net.
+ * InetAddress)
*/
public boolean contains(final InetAddress ip) {
- if (! InetNetworkBuilder.isV6(ip.getHostAddress())) {
+ if (!InetNetworkBuilder.isV6(ip.getHostAddress())) {
return false;
}
try {
return network.equals(maskIP(ip, netmask));
- }
- catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
return false;
}
}
@@ -88,19 +93,16 @@ public class Inet6Network implements Ine
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
- return (obj != null)
- && (obj instanceof InetNetwork)
- && ((((Inet6Network) obj).network.equals(network)) && (((Inet6Network) obj).netmask.equals(netmask)));
+ return (obj != null) && (obj instanceof InetNetwork) && ((((Inet6Network) obj).network.equals(network)) && (((Inet6Network) obj).netmask.equals(netmask)));
}
-
/**
* @see #maskIP(byte[], byte[])
*/
private static InetAddress maskIP(final InetAddress ip, Integer mask) {
byte[] maskBytes = new byte[16];
int i = 0;
- while (mask > 0) {
+ while (mask > 0) {
maskBytes[i] = (byte) 255;
i++;
mask = (mask >> 1);
@@ -109,11 +111,13 @@ public class Inet6Network implements Ine
}
/**
- * Return InetAddress generated of the passed arguments.
- * Return Null if any error occurs
+ * Return InetAddress generated of the passed arguments. Return Null if any
+ * error occurs
*
- * @param ip the byte[] represent the ip
- * @param mask the byte[] represent the netmask
+ * @param ip
+ * the byte[] represent the ip
+ * @param mask
+ * the byte[] represent the netmask
* @return inetAddress the InetAddress generated of the passed arguments.
*/
private static InetAddress maskIP(final byte[] ip, final byte[] mask) {
@@ -125,7 +129,7 @@ public class Inet6Network implements Ine
}
try {
byte[] maskedIp = new byte[ip.length];
- for (int i=0; i < ip.length; i++) {
+ for (int i = 0; i < ip.length; i++) {
maskedIp[i] = (byte) (ip[i] & mask[i]);
}
return getByAddress(maskedIp);
@@ -145,30 +149,16 @@ public class Inet6Network implements Ine
private static InetAddress getByAddress(byte[] ip) throws UnknownHostException {
InetAddress addr = Inet6Address.getByAddress(ip);
-
+
// TODO Don't know if this is correct?
if (addr == null) {
- addr = InetAddress.getByName(
- Integer.toString(ip[0] & 0xFF, 10) + ":"
- + Integer.toString(ip[1] & 0xFF, 10) + ":"
- + Integer.toString(ip[2] & 0xFF, 10) + ":"
- + Integer.toString(ip[3] & 0xFF, 10) + ":"
- + Integer.toString(ip[4] & 0xFF, 10) + ":"
- + Integer.toString(ip[5] & 0xFF, 10) + ":"
- + Integer.toString(ip[6] & 0xFF, 10) + ":"
- + Integer.toString(ip[7] & 0xFF, 10) + ":"
- + Integer.toString(ip[8] & 0xFF, 10) + ":"
- + Integer.toString(ip[9] & 0xFF, 10) + ":"
- + Integer.toString(ip[10] & 0xFF, 10) + ":"
- + Integer.toString(ip[11] & 0xFF, 10) + ":"
- + Integer.toString(ip[12] & 0xFF, 10) + ":"
- + Integer.toString(ip[13] & 0xFF, 10) + ":"
- + Integer.toString(ip[14] & 0xFF, 10) + ":"
- + Integer.toString(ip[15] & 0xFF, 10));
+ addr = InetAddress.getByName(Integer.toString(ip[0] & 0xFF, 10) + ":" + Integer.toString(ip[1] & 0xFF, 10) + ":" + Integer.toString(ip[2] & 0xFF, 10) + ":" + Integer.toString(ip[3] & 0xFF, 10) + ":" + Integer.toString(ip[4] & 0xFF, 10) + ":" + Integer.toString(ip[5] & 0xFF, 10) + ":"
+ + Integer.toString(ip[6] & 0xFF, 10) + ":" + Integer.toString(ip[7] & 0xFF, 10) + ":" + Integer.toString(ip[8] & 0xFF, 10) + ":" + Integer.toString(ip[9] & 0xFF, 10) + ":" + Integer.toString(ip[10] & 0xFF, 10) + ":" + Integer.toString(ip[11] & 0xFF, 10) + ":"
+ + Integer.toString(ip[12] & 0xFF, 10) + ":" + Integer.toString(ip[13] & 0xFF, 10) + ":" + Integer.toString(ip[14] & 0xFF, 10) + ":" + Integer.toString(ip[15] & 0xFF, 10));
}
-
+
return addr;
-
+
}
}
Modified: james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/InetNetwork.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/InetNetwork.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/InetNetwork.java (original)
+++ james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/inetnetwork/model/InetNetwork.java Mon Apr 4 14:59:11 2011
@@ -21,18 +21,20 @@ package org.apache.james.dnsservice.libr
import java.net.InetAddress;
/**
- * An InetNetwork represents a IPv4 or IPv6 address with a subnet mask.<br/>
+ * An InetNetwork represents a IPv4 or IPv6 address with a subnet mask.<br>
* The subnet mask allows to represent one or more host (a "network of hosts").
*
- * Do not confuse the InetAddress.toString() returning a "hostname/ip_address" (optional hostname)
- * with the InetNetwork.toString() that returns a "ip_address/subnet_mask".
+ * Do not confuse the InetAddress.toString() returning a "hostname/ip_address"
+ * (optional hostname) with the InetNetwork.toString() that returns a
+ * "ip_address/subnet_mask".
*/
public interface InetNetwork {
/**
* Return true if the network contains the given name
*
- * @param name hostname or ipAddress
+ * @param name
+ * hostname or ipAddress
* @return true if the network contains the ip address
*/
boolean contains(InetAddress ip);
Modified: james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/netmatcher/NetMatcher.java
URL: http://svn.apache.org/viewvc/james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/netmatcher/NetMatcher.java?rev=1088657&r1=1088656&r2=1088657&view=diff
==============================================================================
--- james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/netmatcher/NetMatcher.java (original)
+++ james/server/trunk/dnsservice-library/src/main/java/org/apache/james/dnsservice/library/netmatcher/NetMatcher.java Mon Apr 4 14:59:11 2011
@@ -33,11 +33,11 @@ import org.apache.james.dnsservice.libra
/**
* NetMatcher Class is used to check if an ipAddress match a network.
*
- * NetMatcher provides a means for checking whether
- * a particular IPv4 or IPv6 address or domain name is within a set of subnets.
+ * NetMatcher provides a means for checking whether a particular IPv4 or IPv6
+ * address or domain name is within a set of subnets.
*/
public class NetMatcher {
-
+
/**
* The DNS Service used to build InetNetworks.
*/
@@ -51,8 +51,10 @@ public class NetMatcher {
/**
* Create a new instance of Netmatcher.
*
- * @param nets a String[] which holds all networks
- * @param dnsServer the DNSService which will be used in this class
+ * @param nets
+ * a String[] which holds all networks
+ * @param dnsServer
+ * the DNSService which will be used in this class
*/
public NetMatcher(final String[] nets, DNSService dnsServer) {
this.dnsServer = dnsServer;
@@ -62,8 +64,10 @@ public class NetMatcher {
/**
* Create a new instance of Netmatcher.
*
- * @param nets a Collection which holds all networks
- * @param dnsServer the DNSService which will be used in this class
+ * @param nets
+ * a Collection which holds all networks
+ * @param dnsServer
+ * the DNSService which will be used in this class
*/
public NetMatcher(final Collection<String> nets, DNSService dnsServer) {
this.dnsServer = dnsServer;
@@ -73,11 +77,12 @@ public class NetMatcher {
/**
* The given String may represent an IP address or a host name.
*
- * @param hostIP the ipAddress or host name to check
+ * @param hostIP
+ * the ipAddress or host name to check
* @see #matchInetNetwork(InetAddress)
*/
public boolean matchInetNetwork(final String hostIP) {
-
+
InetAddress ip = null;
try {
@@ -92,23 +97,24 @@ public class NetMatcher {
}
/**
- * Return true if passed InetAddress match a network which
- * was used to construct the Netmatcher.
+ * Return true if passed InetAddress match a network which was used to
+ * construct the Netmatcher.
*
- * @param an InetAddress
+ * @param an
+ * InetAddress
* @return true if match the network
*/
public boolean matchInetNetwork(final InetAddress ip) {
-
+
boolean sameNet = false;
for (Iterator<InetNetwork> iter = networks.iterator(); (!sameNet) && iter.hasNext();) {
InetNetwork network = iter.next();
sameNet = network.contains(ip);
}
-
+
return sameNet;
-
+
}
/**
@@ -123,24 +129,27 @@ public class NetMatcher {
/**
* Can be overwritten for logging
*
- * @param s the String to log
+ * @param s
+ * the String to log
*/
protected void log(String s) {
}
-
+
/**
* Init the class with the given networks.
*
- * @param nets a Collection which holds all networks
+ * @param nets
+ * a Collection which holds all networks
*/
private void initInetNetworks(final Collection<String> nets) {
- initInetNetworks(nets.toArray(new String[]{}));
+ initInetNetworks(nets.toArray(new String[] {}));
}
/**
* Init the class with the given networks.
*
- * @param nets a String[] which holds all networks
+ * @param nets
+ * a String[] which holds all networks
*/
private void initInetNetworks(final String[] nets) {
@@ -152,7 +161,7 @@ public class NetMatcher {
final InetNetworkBuilder inetNetwork = new InetNetworkBuilder(dnsServer);
- for (String net: nets) {
+ for (String net : nets) {
try {
InetNetwork inet = inetNetwork.getFromString(net);
networks.add(inet);
@@ -160,7 +169,7 @@ public class NetMatcher {
log("Cannot resolve address: " + uhe.getMessage());
}
}
-
+
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org