/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.jetspeed.om.security.ldap;

import org.apache.jetspeed.services.JetspeedUserManagement;
import org.apache.jetspeed.services.JetspeedAuthentication;
import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.turbine.om.security.User;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Date;
import java.util.Hashtable;
import javax.servlet.http.HttpSessionBindingEvent;
import org.apache.turbine.util.Log;
import org.apache.turbine.util.ObjectUtils;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.jetspeed.services.JetspeedLDAP;
import org.apache.jetspeed.services.security.ldap.UnixCrypt;
import org.apache.jetspeed.services.ldap.LDAPURL;
import org.apache.jetspeed.util.Base64;
import javax.naming.*;
import javax.naming.directory.*;
import java.io.*;

/**
 *
 * @author <a href="mailto:ender@kilicoglu.nom.tr">Ender KILICOGLU</a>
 * @author <a href="mailto:sami.leino@netorek.fi">Sami Leino</a>
 * 
 * @version $Id: LDAPUser.java,v 1.3 2002/12/09 20:24:08 taylor Exp $ 
 * 
 */
public class LDAPUser extends BaseLDAPObject implements JetspeedUser {

    // ---------------------------- Constants ----------------------------

    protected static final String OBJECT_CLASS           = "jetspeedpermission";
    protected static final String ORGANIZATIONAL_UNIT    = "ou=permissions";

    protected static final String ATTR_USER_ID           = "uid";
    protected static final String ATTR_OBJECT_DATA       = "objectdata";

	protected static final boolean SAVE_EXTRA_ATTRIBUTES = false;
    protected static final String LDAP_DATE_PATTERN      = "yyyy.MM.dd G 'at' hh:mm:ss a zzz";

    // ------------------------- Member variables ------------------------

    /** The date on which the user account was created. */
    private Date createDate = null;

    /** The date on which the user last accessed the application. */
    private Date lastAccessDate = null;

    /** The date on which the user last changed his password. */
    private Date passwordChanged = null;

    /** This is data that will survive a servlet engine restart. */
    private Hashtable permStorage = null;

    /** This is data that will not survive a servlet engine restart. */
    private Hashtable tempStorage = null;

    protected String name = "";

    protected boolean isNew = false;

    private Vector groupRoles = null;

    // --------------------------- Constructors --------------------------

    public LDAPUser()
    {
        this("TempUser", true);
    }

    /**
     * Constructor.
     * Create a new User and set the createDate.
     */
    public LDAPUser(String username, boolean isNew)
    {
        ldapurl = JetspeedLDAP.buildURL("uid=" + username + ",ou=users");
        this.isNew = isNew;

        createDate = new Date();
        lastAccessDate = createDate;
        tempStorage = new Hashtable(10);
        permStorage = new Hashtable(10);
        groupRoles = new Vector();
        setHasLoggedIn(Boolean.FALSE);

        if (isNew)
        {
            setDisabled(false);
            setUserName(username);
            myAttrs = new BasicAttributes();
            myAttrs.put("uid", username);
            Attribute oc = new BasicAttribute("objectclass");
            oc.add("jetspeeduser");
            myAttrs.put(oc);
        }
        else
        {
            myAttrs =  JetspeedLDAP.read(ldapurl);
            setName(getutil("name"));
            setEmail(getutil("mail"));
            setFirstName(getutil("givenName"));
            setLastName(getutil("sn"));
            setUserName(username);
            this.groupRoles = getutil("usergrouprole", true);

            setLastLogin(parseDate(getutil("lastlogindate")));
            lastAccessDate = parseDate(getutil("lastmodifieddate"));
            setCreateDate(parseDate(getutil("creationdate")));
            String temp = getutil("disabled");
            if (temp != null && temp.equals("TRUE")) setDisabled(true);
            else setDisabled(false);

            try
            {
                setPermStorage(deserializePerm(getutil(ATTR_OBJECT_DATA)));
            }
            catch (Exception e)
            {
            }
        }
    }

    public LDAPUser( LDAPURL ldapurl )
    {
        createDate = new Date();
        tempStorage = new Hashtable(10);
        permStorage = new Hashtable(10);
        setHasLoggedIn(Boolean.FALSE);
        groupRoles = new Vector();
        this.ldapurl = ldapurl;
        myAttrs =  JetspeedLDAP.read(ldapurl);

        try
        {
            setPermStorage(deserializePerm(getutil(ATTR_OBJECT_DATA)));
        }
        catch (Exception e)
        {
        }
    
        setUserName(getutil("uid"));
        setEmail(getutil("mail"));
        setFirstName(getutil("givenName"));
        setLastName(getutil("sn"));
        setName(getutil("name"));
        setConfirmed(getutil("confirm"));
    
            setLastLogin(parseDate(getutil("lastlogindate")));
            lastAccessDate = parseDate(getutil("lastmodifieddate"));
            setCreateDate(parseDate(getutil("creationdate")));
            String temp = getutil("disabled");
            if (temp != null && temp.equals("TRUE")) setDisabled(true);
            else setDisabled(false);

        try
        {
            setPassword(new String ((byte[]) myAttrs.get("userPassword").getAll().nextElement()));
        }
        catch (Exception e)
        {
        }
    
        this.groupRoles = getutil( "usergrouprole", true );
    }

    // --------------------- Persistence operations ----------------------

    public boolean update(boolean create)
    {
        removeutil("createTimeStamp", false);
        removeutil("modifyTimeStamp", false);

        setutil("userPassword",(String)getPerm(User.PASSWORD) );
        setutil("mail",(String)getPerm(User.EMAIL));
        setutil("confirm",(String)getPerm(User.CONFIRM_VALUE));
        setutil("sn",(String)getPerm(User.LAST_NAME));
        setutil("givenName",(String)getPerm(User.FIRST_NAME));

        setutil("usergrouprole", groupRoles);

        if (SAVE_EXTRA_ATTRIBUTES)
		{
	        try
	        {
	            setutil("lastlogindate", formatDate(getLastLogin()));
	            setutil("lastmodifieddate", formatDate(getLastAccessDate()));
	            setutil("creationdate", formatDate(getCreateDate()));
	            if (getDisabled() == true) setutil("disabled", "TRUE");
	            else setutil("disabled", "FALSE");
	            setutil(ATTR_OBJECT_DATA, serializePerm(permStorage));
	        }
	        catch (Exception e)
	        {
	            Log.warn("Setting extra user attributes failed!", e); 
	        }
		}

        if (JetspeedLDAP.exists(ldapurl))
        {
            JetspeedLDAP.deleteAttrs(ldapurl, rmAttrs);
            JetspeedLDAP.updateEntry(ldapurl, myAttrs);
        }
        else if (create)
        {
            ldapurl = JetspeedLDAP.buildURL("uid=" + (String)getPerm(User.USERNAME) + ",ou=users");
            setutil("uid", (String)getPerm(User.USERNAME));
            JetspeedLDAP.addEntry(ldapurl,myAttrs);
        }
        else
        {
            return false;
        }

        return true;
    }

    // ----------------------- Utility operations ------------------------

    protected String formatDate(Date date)
    {
        if (date == null)
        {
            date = new Date();
        }

        SimpleDateFormat formatter = new SimpleDateFormat(LDAP_DATE_PATTERN);
        return formatter.format(date);
    }

    protected Date parseDate(String value)
    {
        try
        {
            SimpleDateFormat parser = new SimpleDateFormat(LDAP_DATE_PATTERN);
            return parser.parse(value);
        }
        catch (Exception e)
        {
            return new Date();
        }
    }

    /*
    protected byte[] serializePerm(Hashtable permStorage)
    throws Exception
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(permStorage);
        return baos.toByteArray();
    }

    protected Hashtable deserializePerm(byte[] permStorageContentsEncoded)
    throws Exception
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(permStorageContentsEncoded);
        ObjectInputStream is = new ObjectInputStream(bais);
        return (Hashtable)is.readObject();
    }
    */

    protected String serializePerm(Hashtable permStorage)
    throws Exception
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(permStorage);
        return Base64.encodeAsString(baos.toByteArray());
    }

    protected Hashtable deserializePerm(String permStorageContentsEncoded)
    throws Exception
    {
        byte[] decoded = Base64.decodeAsByteArray(permStorageContentsEncoded);
        ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
        ObjectInputStream is = new ObjectInputStream(bais);
        return (Hashtable)is.readObject();
    }

    // ------------------------ Accessor methods -------------------------

    public Vector getGroupRoles()
    {
        return this.groupRoles;
    }

    public void addGroupRole(String groupName, String roleName)
    {
        groupRoles.add(groupName + "," + roleName);
    }

    public void removeGroup(String groupName)
    {
        for (Enumeration enum = groupRoles.elements();enum.hasMoreElements();)
        {
            String groupRoleStr = (String)enum.nextElement();
            if (groupRoleStr.startsWith(groupName + ","))
            {
                groupRoles.remove(groupRoleStr);
            }
        }
    }

    public void removeGroupRoles(String groupName, String roleName)
    {
        for (Enumeration enum = groupRoles.elements(); enum.hasMoreElements();)
        {
            String groupRoleStr = (String)enum.nextElement();
            if (groupRoleStr.equalsIgnoreCase(groupName + "," + roleName))
            {
                groupRoles.remove(groupRoleStr);
            }
        }
    }

    /**
     * Returns the primary principle for this User, the user id.
     *
     * @return the user id.
     */
    public String getUserId()
    {
        String tmp = null;

        try
        {
            tmp = (String) getPerm (JetspeedUser.USER_ID);
            if ( tmp.length() == 0 )
            {
                tmp = null;
            }
        }
        catch (Exception e)
        {
        }
        return tmp;
    }

    public void setUserId(String id)
    {
        if (getUserId() == null)
        {
            setPerm(JetspeedUser.USER_ID, id);
        }
    }
    /**
     * Gets the access counter for a user during a session.
     *
     * @return The access counter for the user for the session.
     */
    public int getAccessCounterForSession()
    {
        try
        {
            return ((Integer) getTemp(User.SESSION_ACCESS_COUNTER)).intValue();
        }
        catch (Exception e)
        {
            return 0;
        }
    }

    /**
     * Gets the access counter for a user from perm storage.
     *
     * @return The access counter for the user.
     */
    public int getAccessCounter()
    {
        try
        {
            return ((Integer) getPerm(User.ACCESS_COUNTER)).intValue();
        }
        catch (Exception e)
        {
            return 0;

        }
    }

    /**
     * Gets the create date for this User.  This is the time at which
     * the user object was created.
     *
     * @return A Java Date with the date of creation for the user.
     */
    public java.util.Date getCreateDate()
    {
        return createDate;
    }

    /**
     * Gets the last access date for this User.  This is the last time
     * that the user object was referenced.
     *
     * @return A Java Date with the last access date for the user.
     */
    public java.util.Date getLastAccessDate()
    {
        if (lastAccessDate == null)
        {
            setLastAccessDate();
        }
        return lastAccessDate;
    }

    /**

     * Get last login date/time for this user.
     *
     * @return A Java Date with the last login date for the user.
     */
    public java.util.Date getLastLogin()
    {
        return (java.util.Date) getPerm(User.LAST_LOGIN);
    }

    /**
     * Get password for this user.
     *
     * @return A String with the password for the user.
     */
    public String getPassword()
    {
        return (String) getPerm(User.PASSWORD);
    }

    /**
     * Get an object from permanent storage.
     *
     * @param name The object's name.
     * @return An Object with the given name.
     */
    public Object getPerm(String name)
    {
        return permStorage.get(name);
    }

    /**
     * Get an object from permanent storage; return default if value
     * is null.
     *
     * @param name The object's name.
     * @param def A default value to return.
     * @return An Object with the given name.
     */
    public Object getPerm(String name, Object def)
    {
        try
        {
            Object val = permStorage.get (name);

            return (val == null ? def : val);
        }
        catch (Exception e)
        {
            return def;
        }
    }

    /**
     * This should only be used in the case where we want to save the
     * data to the database.
     *
     * @return A Hashtable.
     */
    public Hashtable getPermStorage()
    {
        if (this.permStorage == null)
        {
            this.permStorage = new Hashtable();
        }
        return this.permStorage;
    }

    /**
     * Get an object from temporary storage.
     *
     * @param name The object's name.
     * @return An Object with the given name.
     */
    public Object getTemp(String name)
    {
        return tempStorage.get(name);
    }

    /**
     * Get an object from temporary storage; return default if value
     * is null.
     *
     * @param name The object's name.
     * @param def A default value to return.
     * @return An Object with the given name.
     */
    public Object getTemp(String name, Object def)
    {
        Object val;
        try
        {
            val = tempStorage.get(name);
            if (val == null)
            {
                val = def;
            }
        }
        catch (Exception e)
        {
            val = def;
        }
        return val;

    }

    /**
     * Returns the username for this user.  If this is defined, then
     * the user is considered logged in.
     *
     * @return A String with the username.
     */
    public String getUserName()
    {
        String tmp = null;
        try
        {
            tmp = (String) getPerm (User.USERNAME);
            if ( tmp.length() == 0 )
            {
                tmp = null;
            }
        }
        catch (Exception e)
        {
        }
        return tmp;
    }

    /**
     * Returns the first name for this user.  If this is defined, then
     * the user is considered logged in.
     *
     * @return A String with the user's first name.
     */
    public String getFirstName()
    {
        String tmp = null;
        try
        {
            tmp = (String) getPerm (User.FIRST_NAME);
            if (tmp.length() == 0)
            {
                tmp = null;
            }
        }
        catch (Exception e)
        {
        }
        return tmp;
    }

    /**
     * Returns the last name for this user.  If this is defined, then
     * the user is considered logged in.
     *
     * @return A String with the user's last name.
     */
    public String getLastName()
    {
        String tmp = null;
        try
        {
            tmp = (String) getPerm (User.LAST_NAME);
            if (tmp.length() == 0) tmp = null;
        }
        catch (Exception e)


        {
        }
        return tmp;
    }

    /**
     * The user is considered logged in if they have not timed out.

     *
     * @return Whether the user has logged in.
     */
    public boolean hasLoggedIn()
    {
        Boolean loggedIn = getHasLoggedIn();
        return (loggedIn != null && loggedIn.booleanValue());
    }

    /**
     * Returns the email address for this user.

     *
     * @return A String with the user's email address.
     */
    public String getEmail()
    {
        return (String)getPerm(User.EMAIL);
    }

    /**
     * Increments the permanent hit counter for the user.
     */
    public void incrementAccessCounter()
    {
        setAccessCounter(getAccessCounter() + 1);
    }

    /**
     * Increments the session hit counter for the user.
     */
    public void incrementAccessCounterForSession()
    {
        setAccessCounterForSession(getAccessCounterForSession() + 1);
    }

    /**
     * Remove an object from temporary storage and return the object.
     *
     * @param name The name of the object to remove.
     * @return An Object.
     */
    public Object removeTemp(String name)
    {
        return tempStorage.remove(name);
    }

    /**
     * Sets the access counter for a user, saved in perm storage.
     *
     * @param cnt The new count.
     */
    public void setAccessCounter(int cnt)
    {
        setPerm(User.ACCESS_COUNTER, new Integer(cnt));
    }

    /**
     * Sets the session access counter for a user, saved in temp
     * storage.
     *
     * @param cnt The new count.
     */
    public void setAccessCounterForSession(int cnt)
    {
        setTemp(User.SESSION_ACCESS_COUNTER, new Integer(cnt));
    }

    /**
     * Sets the last access date for this User. This is the last time
     * that the user object was referenced.
     */
    public void setLastAccessDate()
    {
        lastAccessDate = new java.util.Date();
    }

    /**
     * Sets the create date for this User. This is the time at which
     * the user object was created.
     *
     * @param date The create date.
     */
    public void setCreateDate(java.util.Date date)
    {
        createDate = date;
    }

    /**
     * Set last login date/time.
     *
     * @param date The last login date.
     */
    public void setLastLogin(java.util.Date date)
    {
        setPerm(User.LAST_LOGIN, date);
    }

    /**
     * Set password.
     *
     * @param password The new password.
     */
    public void setPassword(String password)
    {
        setPerm(User.PASSWORD, password);
    }

    /**
     * Put an object into permanent storage. If the value is null,
     * it will convert that to a "" because the underlying storage
     * mechanism within TurbineUser is currently a Hashtable and
     * null is not a valid value.
     *
     * @param name The object's name.
     * @param value The object.
     */
    public void setPerm(String name, Object value)
    {
        ObjectUtils.safeAddToHashtable(getPermStorage(), name, value);
    }

    /**
     * This should only be used in the case where we want to save the
     * data to the database.
     *
     * @param stuff A Hashtable.
     */
    public void setPermStorage(Hashtable stuff)
    {
        this.permStorage = stuff;
    }

    /**
     * This should only be used in the case where we want to save the
     * data to the database.
     *
     * @return A Hashtable.
     */
    public Hashtable getTempStorage()
    {
        if (this.tempStorage == null)
        {
            this.tempStorage = new Hashtable();
        }
        return this.tempStorage;
    }

    /**
     * This should only be used in the case where we want to save the
     * data to the database.
     *
     * @param storage A Hashtable.
     */
    public void setTempStorage(Hashtable storage)
    {
        this.tempStorage = storage;
    }

    /**
     * This gets whether or not someone has logged in.  hasLoggedIn()
     * returns this value as a boolean.  This is private because you
     * should use hasLoggedIn() instead.
     *
     * @return True if someone has logged in.
     */
    private Boolean getHasLoggedIn()
    {
        return (Boolean) getTemp (User.HAS_LOGGED_IN);
    }

    /**
     * This sets whether or not someone has logged in.  hasLoggedIn()
     * returns this value.
     *
     * @param value Whether someone has logged in or not.
     */
    public void setHasLoggedIn (Boolean value)
    {
        setTemp (User.HAS_LOGGED_IN, value);
    }

    /**
     * Put an object into temporary storage. If the value is null,
     * it will convert that to a "" because the underlying storage
     * mechanism within TurbineUser is currently a Hashtable and
     * null is not a valid value.
     *
     * @param name The object's name.
     * @param value The object.
     */
    public void setTemp(String name, Object value)
    {
        ObjectUtils.safeAddToHashtable(tempStorage, name, value);
    }

    /**
     * Sets the username for this user.
     *
     * @param username The user's username.
     */
    public void setUserName(String username)
    {
        setPerm (User.USERNAME, username);
    }

    /**
     * Sets the first name for this user.
     *
     * @param firstName User's first name.
     */
    public void setFirstName(String firstName)
    {
        setPerm(User.FIRST_NAME, firstName);
    }

    /**
     * Sets the last name for this user.
     *
     * @param lastName User's last name.
     */
    public void setLastName(String lastName)
    {
        setPerm(User.LAST_NAME, lastName);
    }

    /**
     * Sets the email address.
     *
     * @param address The email address.
     */
    public void setEmail(String address)
    {
        setPerm(User.EMAIL, address);
    }

    /**
     * This method reports whether or not the user has been confirmed
     * in the system by checking the User.CONFIRM_VALUE
     * column in the users record to see if it is equal to
     * User.CONFIRM_DATA.
     *
     * @return True if the user has been confirmed.
     */
    public boolean isConfirmed()
    {
        String value = getConfirmed();
        return (value != null && value.equals(User.CONFIRM_DATA));
    }

    /**
     * Sets the confirmation value. The value should
     * be either a random string or User.CONFIRM_DATA
     *
     * @param value The confirmation key value.
     */
    public void setConfirmed(String value)
    {
        String val = "";
        if (value != null)
        {
            val = value;
        }
        setPerm(User.CONFIRM_VALUE, val);
    }

    /**
     * Gets the confirmation value.
     *
     * @return status The confirmation value for this User
     */
    public String getConfirmed()
    {
        return (String)getPerm(User.CONFIRM_VALUE);
    }

    /**
     * Updates the last login date in the database.
     *
     * @exception Exception, a generic exception.
     */
    public void updateLastLogin()
        throws Exception
    {
        setPerm( User.LAST_LOGIN, new java.util.Date() );
    }

    /**
     * Implement this method if you wish to be notified when the User
     * has been Bound to the session.
     *
     * @param hsbe The HttpSessionBindingEvent.
     */
    public void valueBound(HttpSessionBindingEvent hsbe)
    {
        // Currently we have no need for this method.
    }

    /**
     * Implement this method if you wish to be notified when the User
     * has been Unbound from the session.
     *
     * @param hsbe The HttpSessionBindingEvent.
     */
    public void valueUnbound(HttpSessionBindingEvent hsbe)
    {
        try
        {
            java.util.Date now = new java.util.Date();


            if (this.hasLoggedIn())
            {
                if ( JetspeedResources.getBoolean("automatic.logout.save", false) )
                {
                    JetspeedUserManagement.saveUser(this);
                }
                JetspeedAuthentication.logout();
            }
        }
        catch ( Exception e )
        {
            Log.error("TurbineUser.valueUnbound(): " + e.getMessage(), e);

            // To prevent messages being lost in case the logging system
            // goes away before sessions get unbound on servlet container
            // shutdown, print the stcktrace to the container's console.
            ByteArrayOutputStream ostr = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(ostr,true));
            String stackTrace = ostr.toString();
            System.out.println(stackTrace);
        }
    }

    /**
     * Saves this object to the data store.
     */
    public void save()
        throws Exception
    {
        if (this.isNew())
        {
            JetspeedUserManagement.saveUser(this);
        }
        else
        {
            JetspeedUserManagement.addUser(this);
        }
    }

    /**
     * Returns the disabled status for the user
     *
     * @return True when the account is disabled
     */
    public boolean getDisabled()
    {
        boolean disabled = false;
        try
        {
            String tmp = (String) getPerm (JetspeedUser.DISABLED);
            if ( tmp != null && tmp.length() > 0 )
            {
                if (tmp.equalsIgnoreCase("T"))
                disabled = true;
            }
        }
        catch (Exception e)
        {
        }
        return disabled;
    }

    public void setDisabled(boolean disabled)
    {
        setPerm(JetspeedUser.DISABLED, (disabled) ? "T" : "F");
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }


    public boolean isNew()
    {
        return isNew;
    }

    void setNew(boolean isNew)
    {
        this.isNew = isNew;
    }

    /**
     * Returns the date of last password change
     *
     * @return date

     */
    public Date getPasswordChanged()
    {
        return this.passwordChanged;
    }
 
    /**
     * Sets the date of last password change
     * 
     * @param value  Date
     */
    public void setPasswordChanged(Date value)
    {
        this.passwordChanged = value;
    }

}
