Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 1999,2004 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 
 package org.apache.catalina.realm;
 
 
 import java.io.File;
 import  org.apache.catalina.Container;
 import  org.apache.catalina.LifecycleException;
 import  org.apache.catalina.util.StringManager;
 import  org.apache.commons.logging.Log;
 import  org.apache.commons.logging.LogFactory;
 import  org.apache.tomcat.util.digester.Digester;


Simple implementation of Realm that reads an XML file to configure the valid users, passwords, and roles. The file format (and default file location) are identical to those currently supported by Tomcat 3.X.

IMPLEMENTATION NOTE: It is assumed that the in-memory collection representing our defined users (and their roles) is initialized at application startup and never modified again. Therefore, no thread synchronization is performed around accesses to the principals collection.

Author(s):
Craig R. McClanahan
Version:
$Revision: 1.7 $ $Date: 2004/09/24 07:25:07 $
 
 
 public class MemoryRealm  extends RealmBase {
 
     private static Log log = LogFactory.getLog(MemoryRealm.class);
 
     // ----------------------------------------------------- Instance Variables
 

    
The Container with which this Realm is associated.
 
     private Container container = null;


    
The Digester we will use to process in-memory database files.
 
     private static Digester digester = null;


    
Descriptive information about this Realm implementation.
 
     protected final String info =
         "org.apache.catalina.realm.MemoryRealm/1.0";


    
Descriptive information about this Realm implementation.
 
 
     protected static final String name = "MemoryRealm";


    
The pathname (absolute or relative to Catalina's current working directory) of the XML file containing our database information.
 
     private String pathname = "conf/tomcat-users.xml";


    
The set of valid Principals for this Realm, keyed by user name.
 
     private HashMap principals = new HashMap();


    
The string manager for this package.
 
     private static StringManager sm =
         StringManager.getManager(Constants.Package);


    
Has this component been started?
    private boolean started = false;
    // ------------------------------------------------------------- Properties


    
Return descriptive information about this Realm implementation and the corresponding version number, in the format <description>/<version>.
    public String getInfo() {
        return ;
    }


    
Return the pathname of our XML file containing user definitions.
    public String getPathname() {
        return ;
    }


    
Set the pathname of our XML file containing user definitions. If a relative pathname is specified, it is resolved against "catalina.base".

Parameters:
pathname The new pathname
    public void setPathname(String pathname) {
        this. = pathname;
    }
    // --------------------------------------------------------- Public Methods


    
Return the Principal associated with the specified username and credentials, if there is one; otherwise return null.

Parameters:
username Username of the Principal to look up
credentials Password or other credentials to use in authenticating this username
    public Principal authenticate(String usernameString credentials) {
        GenericPrincipal principal =
            (GenericPrincipal) .get(username);
        boolean validated = false;
        if (principal != null) {
            if (hasMessageDigest()) {
                // Hex hashes should be compared case-insensitive
                validated = (digest(credentials)
                             .equalsIgnoreCase(principal.getPassword()));
            } else {
                validated =
                    (digest(credentials).equals(principal.getPassword()));
            }
        }
        if (validated) {
            if (.isDebugEnabled())
                .debug(.getString("memoryRealm.authenticateSuccess"username));
            return (principal);
        } else {
            if (.isDebugEnabled())
                .debug(.getString("memoryRealm.authenticateFailure"username));
            return (null);
        }
    }
    // -------------------------------------------------------- Package Methods


    
Add a new user to the in-memory database.

Parameters:
username User's username
password User's password (clear text)
roles Comma-delimited set of roles associated with this user
    void addUser(String usernameString passwordString roles) {
        // Accumulate the list of roles for this user
        ArrayList list = new ArrayList();
        roles += ",";
        while (true) {
            int comma = roles.indexOf(',');
            if (comma < 0)
                break;
            String role = roles.substring(0, comma).trim();
            list.add(role);
            roles = roles.substring(comma + 1);
        }
        // Construct and cache the Principal for this user
        GenericPrincipal principal =
            new GenericPrincipal(thisusernamepasswordlist);
        .put(usernameprincipal);
    }
    // ------------------------------------------------------ Protected Methods


    
Return a configured Digester to use for processing the XML input file, creating a new one if necessary.
    protected synchronized Digester getDigester() {
        if ( == null) {
             = new Digester();
            .setValidating(false);
            .addRuleSet(new MemoryRuleSet());
        }
        return ();
    }


    
Return a short name for this Realm implementation.
    protected String getName() {
        return ();
    }


    
Return the password associated with the given principal's user name.
    protected String getPassword(String username) {
        GenericPrincipal principal =
            (GenericPrincipal) .get(username);
        if (principal != null) {
            return (principal.getPassword());
        } else {
            return (null);
        }
    }


    
Return the Principal associated with the given user name.
    protected Principal getPrincipal(String username) {
        return (Principal.get(username);
    }
    // ------------------------------------------------------ Lifecycle Methods


    
Prepare for active use of the public methods of this Component.

Throws:
LifecycleException if this component detects a fatal error that prevents it from being started
    public synchronized void start() throws LifecycleException {
        // Validate the existence of our database file
        File file = new File();
        if (!file.isAbsolute())
            file = new File(System.getProperty("catalina.base"), );
        if (!file.exists() || !file.canRead())
            throw new LifecycleException
                (.getString("memoryRealm.loadExist",
                              file.getAbsolutePath()));
        // Load the contents of the database file
        if (.isDebugEnabled())
            .debug(.getString("memoryRealm.loadPath",
                             file.getAbsolutePath()));
        Digester digester = getDigester();
        try {
            synchronized (digester) {
                digester.push(this);
                digester.parse(file);
            }
        } catch (Exception e) {
            throw new LifecycleException("memoryRealm.readXml"e);
        } finally {
            digester.reset();
        }
        // Perform normal superclass initialization
        super.start();
    }


    
Gracefully shut down active use of the public methods of this Component.

Throws:
LifecycleException if this component detects a fatal error that needs to be reported
    public synchronized void stop() throws LifecycleException {
        // Perform normal superclass finalization
        super.stop();
        // No shutdown activities required
    }
New to GrepCode? Check out our FAQ X