
package com.jware.util.mail;

import java.util.Hashtable;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 * @author jrmt
 */
public class MXLoockup {

	public MXLoockup() {
		super();
	}

	public static String lookupHost( String domain ) {

	    String mailServer = null;
	    Attribute attr = null;
	    try {
			Hashtable env = new Hashtable();
		    env.put("java.naming.factory.initial",
		            "com.sun.jndi.dns.DnsContextFactory");
//		    env.put("java.naming.provider.url",    "dns://almas02.almas.jp/almas.jp");  // this is for testing
		    
		    DirContext ictx = new InitialDirContext( env );
		    Attributes attrs = ictx.getAttributes( domain, new String[] { "MX" });
		    attr = attrs.get( "MX" );
	    } catch ( Exception e ) {
	    	return( null );
	    }
	    if( attr == null ) {
	    	return( null );
	    }
	    String valueString = attr.toString();
	    String[] values = valueString.split(" "); 
	    if( values.length >= 3 ){
	    	mailServer = values[2].trim();
	    }
	    if( mailServer.endsWith( ",") ){
	    	mailServer = mailServer.substring( 0, mailServer.length()-1 );
	    }
	    	
	    return mailServer;
	    
	}
	
	public static String lookupDomain( String mailaddress ) {
		
		if( mailaddress == null ){
			return mailaddress;
		}
		String domainname = mailaddress; 
		int atIndex = mailaddress.indexOf( "@");
		if( atIndex >= 0 ) {
			domainname = mailaddress.substring( atIndex+1 );
		}
		return domainname;
	}
	
	public static void main( String args[] ) {
	    if( args.length == 0 ) {
	      System.err.println( "Usage: MXLookup host [...]" );
	      System.exit( 99 );
	    }
	    for( int i = 0; i < args.length; i++ ) {
	    	try {
	    		System.out.println( args[i] + " is using " +
	    				lookupHost( args[i] ) + " mail servers" );
	    	}
	    	catch( Exception e ) {
	    		System.out.println(args[i] + " : " + e.getMessage());
	    	}
	    }
	}
	
}
