struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Hajratwala, Nayan (N.)" <nhajr...@ford.com>
Subject RE: jndi as a data source
Date Tue, 10 Sep 2002 18:00:17 GMT
Here's some code that I wrote to use LDAP through the Commons Pooling
mechanism... I'm still trying to figure out a good way to validate the
connection using the validateObject method, so that part is likely not
optimal.

There are 2 classes:
	* LdapConnectionFactory, which implements
BasePoolableObjectFactory
	* HRLdap uses the LdapConnectionFactory

Here is the code that then can use HRLdap:

	HRLdap ldap = new HRLdap();
	ldap.executeCdsIdLookup(cdsId);
	String buCode = ldap.getBusinessUnitCode();
	...
	...
	...

I've tried to strip out some stuff that is only applicable in the
environment here, but hopefully this helps.

I'd be interested in anyone else's feedback on this as well in case i'm
doing something stupid =)


=================================================================
import org.apache.commons.pool.BasePoolableObjectFactory;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 * @version $Revision:   1.1  $
 * @author Nayan Hajratwala <nayan@chikli.com>
 */
public class LdapConnectionFactory extends BasePoolableObjectFactory {

	private static Log logger_ = Log.getInstance();
		
	private static Hashtable env_ = null;

	private static Object lock_ = new Object();

	private Hashtable getEnvironment() {
		if (env_ == null) {
			synchronized(lock_) {
				if (env_ == null) {
					env_ = new Hashtable();

					FrameworkEnvConfig props =
FrameworkEnvConfig.getInstance();
					
	
env_.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
					env_.put(Context.PROVIDER_URL,
"ldap://" + props.getProperty("hronline.ldap.default.host") + 
	
":" + props.getProperty("hronline.ldap.default.port"));
	
env_.put(Context.SECURITY_AUTHENTICATION, "simple");
	
env_.put(Context.SECURITY_PRINCIPAL,
props.getProperty("hronline.ldap.default.auth.dn"));
	
env_.put(Context.SECURITY_CREDENTIALS,
props.getProperty("hronline.ldap.default.auth.pwd"));

					// Ford LDAP servers are version
2 servers.  If we don't specify this, then some strange
					// results occur.  Namely,
Non-ASCII characters are not returned properly.
	
env_.put("java.naming.ldap.version", "2");
				}
			}
		}

		return env_;
	}

	
	public Object makeObject() {

		try {
			return new InitialDirContext(getEnvironment());
		}
		catch (NamingException e )
		{
	 		logger_.error(this, "Exception during creation
of LDAP connection.", e);
			return null;
		}
	}
	public void destroyObject(Object o) {
	
		try {
			((DirContext)o).close();
		}
		catch(NamingException e)
		{
	 		logger_.error(this, "Exception during expire of
LDAP connection.", e);
		}
	}

	public boolean validateObject(Object o) {
		try {
			((DirContext)o).getAttributes("test");
		}
		catch (Exception e) {
			logger_.error(this, "Exception during Ldap
Connection validation");
			return false;
		}

		return true;
	}
	
}
=================================================================

=================================================================
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.StackObjectPool;

import java.util.HashMap;
import java.util.Map;

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchResult;

/**
 * This class provides the necessary methods to obtain LDAP data from
CDS
 * <pre>
 *   Rev 1.27   Aug 27 2002 16:00:32   nhajratw
 *fixes from synchronization code review.
 *
 *   Rev 1.26   Aug 26 2002 14:23:30   nhajratw
 *updates for synchronization fixes, franchiseFactory & search engine.
 * </pre>
 * @version $Revision:   1.27  $
 * @author Nayan Hajratwala <nayan@chikli.com>
 */
public class HRLdap {

	private static final String ATTR_NAME_BUILDING_COUNTRY	= "c";
	private static final String ATTR_NAME_CDSID
= "uid";
	private static final String ATTR_NAME_CN
= "cn";
	private static final String ATTR_NAME_EMP_TYPE
= "employeeType";
	private static final String ATTR_NAME_MAIL
= "mail";
	private static final String ATTR_NAME_PHONE
= "telephoneNumber";
	private static final String[] REQUEST_ATTRIBUTES = new String[]
{
			ATTR_NAME_BUILDING_COUNTRY,
			ATTR_NAME_BUSINESS_UNIT,
			ATTR_NAME_CDSID,
			ATTR_NAME_CN,
			...
			...
			...
		};

	private static Log logger_ = Log.getInstance();

	private static ObjectPool pool_ = new StackObjectPool(new
LdapConnectionFactory());

	// Store all the retrieved values here
	private Attributes attrs_;

	public HRLdap() {
	}

	public void executeGidLookup(String gid) throws NamingException
{

		DirContext ctx = null;
		try {
			ctx = (DirContext)pool_.borrowObject();
			attrs_ = ctx.getAttributes("fordgid=" + gid + ",
ou=Employee, ou=People, o=Ford, c=US", REQUEST_ATTRIBUTES);
		}
		catch (NamingException e) {
			throw e;
		}
		catch (Exception e) {
			// This will never happen due to implementation
of ObjectPool
			logger_.error(this, "An exception occurrect
during executeGidLookup for: " + gid, e);
		}
		finally {
			try {
				pool_.returnObject(ctx);
			}
			catch (Exception e) {
				logger_.error(this, "Could not return
the LdapConnection to the pool after lookup on: " + gid, e);
			}
		}
	}

	public void executeCdsIdLookup(String cdsid) throws
NamingException {

		DirContext ctx = null;

		try {
			ctx = (DirContext)pool_.borrowObject();
			NamingEnumeration e = ctx.search("ou=Employee,
ou=People, o=Ford, c=US",
	
new BasicAttributes("uid", cdsid),
	
REQUEST_ATTRIBUTES);

			// We'll just assume that only one entry was
returned, since cdsid is unique
			// If no results were returned, throw an
exception.
			if (!e.hasMore()) {
				throw new NamingException("No LDAP Info
found for this employee: [" + cdsid + "]");
			}
			else {
				SearchResult result =
(SearchResult)e.next();
				attrs_ = result.getAttributes();
			}
		}
		catch (NamingException e) {
			throw e;
		}
		catch (Exception e) {
			// This will never happen due to implementation
of ObjectPool
			logger_.error(this, "An exception occurrect
during executeCdsLookup for: " + cdsid, e);
		}
		finally {
			try {
				pool_.returnObject(ctx);
			}
			catch (Exception e) {
				logger_.error(this, "Could not return
the LdapConnection to the pool after lookup on: " + cdsid, e);
			}
				
		}
	}

	private String getAttributeAsString(String attrName) {

		String value = "";

		try {
			Attribute attr = attrs_.get(attrName);

			if (attr != null) {
				value = attr.get().toString();
			}
		}
		catch (NamingException e) {
			logger_.error(this, "Exception converting
Attribute [" + attrName + "] to String", e);
		}

		return value;
	}

	public String getCdsId() {
		return getAttributeAsString(ATTR_NAME_CDSID);
	}
	}

	public String getPhoneNumber() {
		return getAttributeAsString(ATTR_NAME_PHONE);
	}

	// An SSN starts with
	public String getSsn() {

		String nid = "";

		try {
			NamingEnumeration e =
attrs_.get(ATTR_NAME_NID).getAll();

			while (e.hasMore()) {
				nid = (String) e.next();

				if (nid.startsWith("01:")) {
					nid = nid.substring(3, 12);
					break;
				}
			}
		}
		catch (NamingException e) {
			logger_.error(this, "There was an error getting
the SSN", e);
		}

		return nid;
	}

	public String getSiteCode() {
		return getAttributeAsString(ATTR_NAME_SITE_CODE);
	}

	public String getEmail() {
		return getAttributeAsString(ATTR_NAME_MAIL);
	}

	public String getGid() {
		return getAttributeAsString(ATTR_NAME_GID);
	}

	public String getMRRole() {
		return getAttributeAsString(ATTR_NAME_MR_ROLE);
	}
}
===========================


---
- Nayan Hajratwala
- Chikli Consulting LLC
- http://www.chikli.com


-----Original Message-----
From: Vincent Stoessel [mailto:vincent@xaymaca.com]
Sent: Tuesday, September 10, 2002 12:14 PM
To: Struts Users Mailing List
Subject: Re: jndi as a data source


I thought it might be cool to use ldap as an authetication mechanism.
Yeah, I saw the tomcat jndi how-to.
I could have sworn that I saw jndi used as a datasource but I could 
haave been tired on that day. I'm still a struts newbie, so I wouldn't 
know how to do cool struts authetication with regular JDBC either.  :)


Galbreath, Mark wrote:
> JNDI operates through your container environment, not Struts.  You can
get
> that information from your app server's docs (specifically) or from
> java.sun.com (generally). What, specifically do you need to know?
> 
> Mark
> 
> -----Original Message-----
> From: Vincent Stoessel [mailto:vincent@xaymaca.com]
> Sent: Tuesday, September 10, 2002 10:26 AM
> To: Struts Users
> Subject: jndi as a data source
> 
> 
> Hello All,
> I'm cuurently searching but can't seem to find a page with an example
> jndi example for struts. I have to build a quick demo app for the
suits. :)
> Any pointers or clue bricks will be appreciated.
> Thanks in advance.
> 
> 


-- 
Vincent Stoessel
Linux Systems Developer
vincent xaymaca.com

Mime
View raw message