Analytics


Google

Tuesday, April 13, 2010

Query LDAP using JNDI

The following is the best example I found that illustrates how to query LDAP using JNDI (in Java).  The code is found here.

One of the key things I found when writing the code is sometimes the attribute that we want may have a null value.  This can be handled by enclosing the code using a try ... catch.

import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;

public class SimpleQuery {

    public static void main(String[] args) {

        if (args.length != 2) {
          System.out.println("Syntax: SimpleQuery query attribute");
          return;
        }

        String query = args[0];
        String attribute = args[1];
        StringBuffer output = new StringBuffer();

        try {
            String url = "ldap://directory.cornell.edu/o=Cornell%20University,c=US";
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, url);
            DirContext context = new InitialDirContext(env);

            SearchControls ctrl = new SearchControls();
            ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
            NamingEnumeration enumeration = context.search("", query, ctrl);
            while (enumeration.hasMore()) {
                SearchResult result = (SearchResult) enumeration.next();
                Attributes attribs = result.getAttributes();
                NamingEnumeration values = ((BasicAttribute) attribs.get(attribute)).getAll();
                while (values.hasMore()) {
                  if (output.length() > 0) {
                    output.append("|");
                  }
                  output.append(values.next().toString());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.print(output.toString());
    }

    public SimpleQuery() {}
}

Sunday, April 11, 2010

Computing and Displaying elapsed time In vb.net

To compute the elapse time, get the snapshot of the time at the beginning, using Now.TimeOfDay (as shown below) and then substract from the same when it is time to display the elapsed time.

         Dim prgStartTime As TimeSpan = Now.TimeOfDay
         Dim eTime As TimeSpan = Now.TimeOfDay.Subtract(prgStartTime)

         Console.WriteLine("Elasped Time " & eTime.ToString)

Saturday, April 10, 2010

Computing and Displaying elapsed time In Java program

To do that capture the start using a long variable as shown below and then compute it against the currentTimeMillis to display.

In the example below, I am displaying in Second.

public static void main(String[] args) {

        // Initialize some parameters
        long stTime = System.currentTimeMillis();
        System.out.println("Elapse time: " + ((System.currentTimeMillis() - stTime) / 1000));
        System.out.println("End Program");

    }