directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From szoer...@apache.org
Subject svn commit: r778169 - /directory/sandbox/szoerner/apacheds-tomcatrealm/src/main/java/org/apache/directory/tomcatrealm/EmbeddedApacheDsRealm.java
Date Sun, 24 May 2009 15:06:16 GMT
Author: szoerner
Date: Sun May 24 15:06:16 2009
New Revision: 778169

URL: http://svn.apache.org/viewvc?rev=778169&view=rev
Log:
Properties added, adhere to directory coding style

Modified:
    directory/sandbox/szoerner/apacheds-tomcatrealm/src/main/java/org/apache/directory/tomcatrealm/EmbeddedApacheDsRealm.java

Modified: directory/sandbox/szoerner/apacheds-tomcatrealm/src/main/java/org/apache/directory/tomcatrealm/EmbeddedApacheDsRealm.java
URL: http://svn.apache.org/viewvc/directory/sandbox/szoerner/apacheds-tomcatrealm/src/main/java/org/apache/directory/tomcatrealm/EmbeddedApacheDsRealm.java?rev=778169&r1=778168&r2=778169&view=diff
==============================================================================
--- directory/sandbox/szoerner/apacheds-tomcatrealm/src/main/java/org/apache/directory/tomcatrealm/EmbeddedApacheDsRealm.java
(original)
+++ directory/sandbox/szoerner/apacheds-tomcatrealm/src/main/java/org/apache/directory/tomcatrealm/EmbeddedApacheDsRealm.java
Sun May 24 15:06:16 2009
@@ -19,6 +19,7 @@
  */
 package org.apache.directory.tomcatrealm;
 
+
 import java.security.Principal;
 import java.text.MessageFormat;
 import java.text.ParseException;
@@ -33,7 +34,6 @@
 import org.apache.directory.server.core.CoreSession;
 import org.apache.directory.server.core.DefaultDirectoryService;
 import org.apache.directory.server.core.DirectoryService;
-import org.apache.directory.server.core.cursor.CursorIterator;
 import org.apache.directory.server.core.entry.ServerEntry;
 import org.apache.directory.server.core.filtering.EntryFilteringCursor;
 import org.apache.directory.server.ldap.LdapService;
@@ -45,251 +45,380 @@
 import org.apache.directory.shared.ldap.message.AliasDerefMode;
 import org.apache.directory.shared.ldap.name.LdapDN;
 
+
 /**
  * An Apache Tomcat realm whichs embeds Apache Directory Server.
  * 
  * @author <a href="mailto:dev@directory.apache.org">Apache Directory
  *         Project</a>
  */
-public class EmbeddedApacheDsRealm extends RealmBase {
+public class EmbeddedApacheDsRealm extends RealmBase
+{
 
-	private static final String REALM_NAME = "EmbeddedApacheDsRealm";
+    private static Log log = LogFactory.getLog( EmbeddedApacheDsRealm.class );
 
-	private static Log log = LogFactory.getLog(EmbeddedApacheDsRealm.class);
+    public static final String REALM_NAME = "EmbeddedApacheDsRealm";
 
-	private DirectoryService directoryService;
+    public static final String DEFAULT_USER_SEARCH_FILTER = "(&(objectClass=inetOrgPerson)(uid={0}))";
 
-	private SocketAcceptor socketAcceptor;
-
-	private LdapService ldapService;
-
-	public EmbeddedApacheDsRealm() {
-	}
-
-	/**
-	 * Startup ApacheDS embedded.
-	 */
-	@Override
-	public void start() throws LifecycleException {
-
-		log.info("Starting Embeded ApacheDS");
-
-		try {
-
-			directoryService = new DefaultDirectoryService();
-			directoryService.setShutdownHookEnabled(true);
-
-			socketAcceptor = new SocketAcceptor(null);
-			ldapService = new LdapService();
-			ldapService.setSocketAcceptor(socketAcceptor);
-			ldapService.setDirectoryService(directoryService);
-
-			// Set LDAP port to 10389
-			ldapService.setIpPort(10389);
-
-			// Determine an appropriate working directory
-			// ??
-
-			directoryService.startup();
-			ldapService.start();
-		} catch (Exception e) {
-			log.error("Starting failed", e);
-			throw new LifecycleException(e);
-		}
-	}
-
-	/**
-	 * Shutdown ApacheDS embedded.
-	 */
-	@Override
-	public void stop() throws LifecycleException {
-
-		log.info("Stopping Embeded ApacheDS");
-
-		try {
-			ldapService.stop();
-			directoryService.shutdown();
-		} catch (Exception e) {
-			log.error("Stopping failed", e);
-			throw new LifecycleException(e);
-		}
-	}
-
-	/**
-	 * Return descriptive information about this Realm implementation and the
-	 * corresponding version number, in the format <description>/<version>.
-	 */
-	@Override
-	public String getInfo() {
-		return REALM_NAME + "/0.1";
-	}
-
-	/**
-	 * Return a short name for this Realm implementation, for use in log
-	 * messages.
-	 */
-	@Override
-	protected String getName() {
-		return REALM_NAME;
-	}
-
-	/**
-	 * Return the Principal associated with the specified username and
-	 * credentials, if there is one; otherwise return null.
-	 */
-	@Override
-	public Principal authenticate(String username, String credentials) {
-
-		Principal principal = null;
-
-		if (log.isDebugEnabled()) {
-			log.debug("Try to authenticate user [" + username + "]");
-		}
-
-		LdapDN userDN = this.searchEntryByUsername(username);
-		if (userDN != null) {
-
-			if (log.isDebugEnabled()) {
-				log.debug("Found user [" + username + "] with DN ["
-						+ userDN.getUpName() + "]");
-			}
-
-			if (this.authenticate(userDN, credentials)) {
-
-				log.debug("Authentication succesful for user [" + username
-						+ "]");
-
-				List<String> roles = this.searchRolesForUserDn(userDN);
-				principal = new GenericPrincipal(this, username, credentials,
-						roles);
-			} else {
-				log.debug("Authentication failed for user " + username);
-			}
-
-		} else {
-			if (log.isDebugEnabled()) {
-				log.debug("User " + username + " not found in directory");
-			}
-		}
-
-		return principal;
-	}
-
-	@Override
-	protected Principal getPrincipal(String username) {
-		return null;
-	}
-
-	/**
-	 * Return the password associated with the given principal's user name. This
-	 * method is not supported by this realm yet.
-	 */
-	@Override
-	protected String getPassword(String username) {
-		throw new RuntimeException(
-				"Operation getPassword not supported by this realm");
-	}
-
-	/**
-	 * Perform a search to find a user entry.
-	 * 
-	 * @param username
-	 *            username, a unique id of the user
-	 * @return DN of the user entry, or null if not found
-	 */
-	protected LdapDN searchEntryByUsername(String username) {
-		LdapDN dn = null;
-
-		try {
-			CoreSession adminSession = directoryService.getAdminSession();
-
-			String base = "ou=system";
-			LdapDN basedn = new LdapDN(base);
-			ExprNode filter = this.createFilter(
-					"(&(objectClass=person)(uid={0}))", username);
-
-			EntryFilteringCursor cursor = adminSession.search(basedn,
-					SearchScope.SUBTREE, filter,
-					AliasDerefMode.NEVER_DEREF_ALIASES, null, 0, 0);			
-			cursor.beforeFirst();
-			if (cursor.next()) {
-				ServerEntry entry = cursor.get();
-				dn = entry.getDn();
-			}
-			cursor.close();
-
-			adminSession.unbind();
-
-		} catch (Exception e) {
-			log.error(e);
-			throw new RuntimeException(e);
-		}
-		return dn;
-	}
-
-	protected boolean authenticate(LdapDN userDN, String credentials) {
-		boolean authenticated = false;
-		try {
-			CoreSession session = directoryService.getSession(userDN, credentials.getBytes());
-			authenticated = true;
-			session.unbind();
-		} catch (Exception e) {
-			// ignored
-		}
-		return authenticated;
-	}
-
-	protected List<String> searchRolesForUserDn(LdapDN userDn) {
-		List<String> roles = new ArrayList<String>();
-
-		if (log.isDebugEnabled()) {
-			log.debug("search roles for user with DN [" + userDn.getUpName()
-					+ "]");
-		}
-
-		try {
-			CoreSession adminSession = directoryService.getAdminSession();
-
-			String base = "ou=system";
-			LdapDN basedn = new LdapDN(base);
-			ExprNode filter = this.createFilter(
-					"(&(objectClass=groupOfNames)(member={0}))", userDn
-							.getUpName());
-
-			EntryFilteringCursor cursor = adminSession.search(basedn,
-					SearchScope.SUBTREE, filter,
-					AliasDerefMode.NEVER_DEREF_ALIASES, null, 0, 0);
-
-			@SuppressWarnings("unchecked")
-			CursorIterator iter = new CursorIterator(cursor);
-			while (iter.hasNext()) {
-				ServerEntry entry = (ServerEntry) iter.next();
-				EntryAttribute attr = entry.get("cn");
-				roles.add(attr.getString());
-			}
-			adminSession.unbind();
-
-		} catch (Exception e) {
-			log.error(e);
-			throw new RuntimeException(e);
-		}
-
-		if (log.isDebugEnabled()) {
-			log.debug(roles.size() + " roles found for user with DN ["
-					+ userDn.getUpName() + "]:" + roles);
-		}
-
-		return roles;
-	}
-
-	protected ExprNode createFilter(String filterPattern, Object... filterArgs)
-			throws ParseException {
-
-		MessageFormat f = new MessageFormat(filterPattern);
-		String sFilter = f.format(filterArgs);
-		ExprNode filter = FilterParser.parse(sFilter);
+    public static final String DEFAULT_USER_SEARCH_BASE = "ou=system";
+
+    public static final String DEFAULT_GROUP_SEARCH_FILTER = "(&(objectClass=groupOfNames)(member={0}))";
+
+    public static final String DEFAULT_GROUP_SEARCH_BASE = "ou=system";
+
+    public static final int DEFAULT_LDAP_PORT = 10389;
+
+    private DirectoryService directoryService;
+
+    private SocketAcceptor socketAcceptor;
+
+    private LdapService ldapService;
+
+    private int ldapPort = DEFAULT_LDAP_PORT;
+
+    private String userSearchFilter = DEFAULT_USER_SEARCH_FILTER;
+
+    private String groupSearchFilter = DEFAULT_GROUP_SEARCH_FILTER;
+
+    private String userSearchBase = DEFAULT_USER_SEARCH_BASE;
+
+    private String groupSearchBase = DEFAULT_GROUP_SEARCH_BASE;
+
+
+    public EmbeddedApacheDsRealm()
+    {
+    }
+
+
+    /**
+     * Startup ApacheDS embedded.
+     */
+    @Override
+    public void start() throws LifecycleException
+    {
+
+        log.info( "Starting Embeded ApacheDS" );
+
+        try
+        {
+
+            directoryService = new DefaultDirectoryService();
+            directoryService.setShutdownHookEnabled( true );
+
+            socketAcceptor = new SocketAcceptor( null );
+            ldapService = new LdapService();
+            ldapService.setSocketAcceptor( socketAcceptor );
+            ldapService.setDirectoryService( directoryService );
+
+            ldapService.setIpPort( this.ldapPort );
+
+            // Determine an appropriate working directory
+            // ??
+
+            directoryService.startup();
+            ldapService.start();
+        }
+        catch ( Exception e )
+        {
+            log.error( "Starting failed", e );
+            throw new LifecycleException( e );
+        }
+    }
+
+
+    /**
+     * Shutdown ApacheDS embedded.
+     */
+    @Override
+    public void stop() throws LifecycleException
+    {
+
+        log.info( "Stopping Embeded ApacheDS" );
+
+        try
+        {
+            ldapService.stop();
+            directoryService.shutdown();
+        }
+        catch ( Exception e )
+        {
+            log.error( "Stopping failed", e );
+            throw new LifecycleException( e );
+        }
+    }
+
+
+    /**
+     * Return descriptive information about this Realm implementation and the
+     * corresponding version number, in the format <description>/<version>.
+     */
+    @Override
+    public String getInfo()
+    {
+        return REALM_NAME + "/0.1";
+    }
+
+
+    /**
+     * Return a short name for this Realm implementation, for use in log
+     * messages.
+     */
+    @Override
+    protected String getName()
+    {
+        return REALM_NAME;
+    }
+
+
+    public String getUserSearchFilter()
+    {
+        return userSearchFilter;
+    }
+
+
+    public void setUserSearchFilter( String userSearchFilter )
+    {
+        this.userSearchFilter = userSearchFilter;
+    }
+
+
+    public String getGroupSearchFilter()
+    {
+        return groupSearchFilter;
+    }
+
+
+    public void setGroupSearchFilter( String groupSearchFilter )
+    {
+        this.groupSearchFilter = groupSearchFilter;
+    }
+
+
+    public String getUserSearchBase()
+    {
+        return userSearchBase;
+    }
+
+
+    public void setUserSearchBase( String userSearchBase )
+    {
+        this.userSearchBase = userSearchBase;
+    }
+
+
+    public String getGroupSearchBase()
+    {
+        return groupSearchBase;
+    }
+
+
+    public void setGroupSearchBase( String groupSearchBase )
+    {
+        this.groupSearchBase = groupSearchBase;
+    }
+
+
+    public int getLdapPort()
+    {
+        return ldapPort;
+    }
+
+
+    public void setLdapPort( int ldapPort )
+    {
+        this.ldapPort = ldapPort;
+    }
+
+
+    /**
+     * Return the Principal associated with the specified username and
+     * credentials, if there is one; otherwise return null.
+     */
+    @Override
+    public Principal authenticate( String username, String credentials )
+    {
+
+        Principal principal = null;
+
+        if ( log.isDebugEnabled() )
+        {
+            log.debug( "Try to authenticate user [" + username + "]" );
+        }
+
+        LdapDN userDN = this.searchEntryByUsername( username );
+        if ( userDN != null )
+        {
+
+            if ( log.isDebugEnabled() )
+            {
+                log.debug( "Found user [" + username + "] with DN [" + userDN.getUpName()
+ "]" );
+            }
+
+            if ( this.authenticate( userDN, credentials ) )
+            {
+
+                log.debug( "Authentication succesful for user [" + username + "]" );
+
+                List<String> roles = this.searchRolesForUserDn( userDN );
+                principal = new GenericPrincipal( this, username, credentials, roles );
+            }
+            else
+            {
+                log.debug( "Authentication failed for user " + username );
+            }
+
+        }
+        else
+        {
+            if ( log.isDebugEnabled() )
+            {
+                log.debug( "User " + username + " not found in directory" );
+            }
+        }
+
+        return principal;
+    }
+
+
+    @Override
+    protected Principal getPrincipal( String username )
+    {
+        return null;
+    }
+
+
+    /**
+     * Return the password associated with the given principal's user name. This
+     * method is not supported by this realm yet.
+     */
+    @Override
+    protected String getPassword( String username )
+    {
+        throw new RuntimeException( "Operation getPassword not supported by this realm" );
+    }
+
+
+    /**
+     * Perform a search to find a user entry.
+     * 
+     * @param username
+     *            username, a unique id of the user
+     * @return DN of the user entry, or null if not found
+     */
+    protected LdapDN searchEntryByUsername( String username )
+    {
+        LdapDN dn = null;
+
+        try
+        {
+            CoreSession adminSession = directoryService.getAdminSession();
+
+            String base = this.userSearchBase;
+            LdapDN basedn = new LdapDN( base );
+            ExprNode filter = this.createFilter( this.userSearchFilter, username );
+
+            EntryFilteringCursor cursor = adminSession.search( basedn, SearchScope.SUBTREE,
filter,
+                AliasDerefMode.NEVER_DEREF_ALIASES, null, 0, 0 );
+            cursor.beforeFirst();
+            if ( cursor.next() )
+            {
+                ServerEntry entry = cursor.get();
+                dn = entry.getDn();
+            }
+            cursor.close();
+            adminSession.unbind();
+
+        }
+        catch ( Exception e )
+        {
+            log.error( e );
+            throw new RuntimeException( e );
+        }
+        return dn;
+    }
+
+
+    protected boolean authenticate( LdapDN userDN, String credentials )
+    {
+        boolean authenticated = false;
+        try
+        {
+            CoreSession session = directoryService.getSession( userDN, credentials.getBytes()
);
+            authenticated = true;
+            session.unbind();
+        }
+        catch ( Exception e )
+        {
+            // ignored
+        }
+        return authenticated;
+    }
+
+
+    protected List<String> searchRolesForUserDn( LdapDN userDn )
+    {
+        List<String> roles = new ArrayList<String>();
+
+        if ( log.isDebugEnabled() )
+        {
+            log.debug( "search roles for user with DN [" + userDn.getUpName() + "]" );
+        }
+
+        try
+        {
+            CoreSession adminSession = directoryService.getAdminSession();
+
+            String base = this.groupSearchBase;
+            LdapDN basedn = new LdapDN( base );
+            ExprNode filter = this.createFilter( this.groupSearchFilter, userDn.getUpName()
);
+
+            EntryFilteringCursor cursor = adminSession.search( basedn, SearchScope.SUBTREE,
filter,
+                AliasDerefMode.NEVER_DEREF_ALIASES, null, 0, 0 );
+
+            cursor.beforeFirst();
+            while ( cursor.next() )
+            {
+                ServerEntry entry = cursor.get();
+                EntryAttribute attr = entry.get( "cn" );
+                roles.add( attr.getString() );
+            }
+            cursor.close();
+            adminSession.unbind();
+
+        }
+        catch ( Exception e )
+        {
+            log.error( e );
+            throw new RuntimeException( e );
+        }
+
+        if ( log.isDebugEnabled() )
+        {
+            log.debug( roles.size() + " roles found for user with DN [" + userDn.getUpName()
+ "]:" + roles );
+        }
+
+        return roles;
+    }
+
+
+    /** 
+     * Creates a filter expression from a filter pattern and a list of arguments. 
+     * For the filter exepression, the MessageFormat style is used. {0} will be replaced
with the first argument.
+     * 
+     * @param filterPattern filter patterns, which contains placeholders {0}, {1} etc for
arguments
+     * @param filterArgs filter argument values
+     * @return the filter
+     * @throws ParseException
+     */
+    protected ExprNode createFilter( String filterPattern, Object... filterArgs ) throws
ParseException
+    {
+
+        MessageFormat f = new MessageFormat( filterPattern );
+        String sFilter = f.format( filterArgs );
+        ExprNode filter = FilterParser.parse( sFilter );
 
-		return filter;
-	}
+        return filter;
+    }
 
 }



Mime
View raw message