/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2003 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.services.security.turbine;

import java.sql.Connection;
import java.util.Iterator;
import java.util.List;
import java.util.HashMap;
import java.util.Vector;

import javax.servlet.ServletConfig;


// Jetspeed Security
import org.apache.jetspeed.services.security.RoleManagement;
import org.apache.jetspeed.services.security.JetspeedSecurityCache;
import org.apache.jetspeed.services.security.CachedAcl;

import org.apache.jetspeed.om.security.JetspeedUser;
import org.apache.jetspeed.om.security.Role;

import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.security.JetspeedSecurityService;
import org.apache.jetspeed.om.security.UserNamePrincipal;

import org.apache.jetspeed.services.PsmlManager;

// Jetspeed Security Exceptions
import org.apache.jetspeed.services.security.RoleException;
import org.apache.jetspeed.services.security.JetspeedSecurityException;


// Jetspeed Database OM
import org.apache.jetspeed.om.security.turbine.TurbineRole;
import org.apache.jetspeed.om.security.turbine.TurbineRolePeer;
import org.apache.jetspeed.om.security.turbine.TurbineRolePermissionPeer;
import org.apache.jetspeed.om.security.turbine.TurbineUserGroupRole;
import org.apache.jetspeed.om.security.turbine.TurbineUserGroupRolePeer;

// Profile
import org.apache.jetspeed.om.profile.Profile;
import org.apache.jetspeed.services.Profiler;
import org.apache.jetspeed.om.profile.ProfileException;

// Jetspeed logging
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;

// Torque
import org.apache.torque.util.Criteria;
import org.apache.torque.om.NumberKey;
import org.apache.torque.Torque;

// Rundata
import org.apache.jetspeed.services.rundata.JetspeedRunDataService;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.turbine.services.rundata.RunDataService;

// Turbine
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.InitializationException;
import org.apache.turbine.services.resources.ResourceService;

/**
 * Default Jetspeed-Turbine Role Management implementation
 *
 *
 * @author <a href="mailto:david@bluesunrise.com">David Sean Taylor</a>
 * @version $Id: TurbineRoleManagement.java,v 1.11 2003/07/23 19:50:24 morciuch Exp $
 */

public class TurbineRoleManagement extends TurbineBaseService
                                   implements RoleManagement
{
    /**
     * Static initialization of the logger for this class
     */    
    private static final JetspeedLogger logger = JetspeedLogFactoryService.getLogger(TurbineRoleManagement.class.getName());
    
    private JetspeedRunDataService runDataService = null;
    private final static String CASCADE_DELETE = "programmatic.cascade.delete";
    private final static String CONFIG_SYSTEM_ROLES = "system.roles";
    private final static boolean DEFAULT_CASCADE_DELETE = true;
    private boolean cascadeDelete;
    private final static String CACHING_ENABLE = "caching.enable";
    private boolean cachingEnable = true;
    private Vector systemRoles = null;


    ///////////////////////////////////////////////////////////////////////////
    // Role Management Interfaces
    ///////////////////////////////////////////////////////////////////////////

    /**
     * Retrieves all <code>Role</code>s for a given username principal.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param username a user principal identity to be retrieved.
     * @return Iterator over all roles associated to the user principal.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Iterator getRoles(String username)
        throws JetspeedSecurityException
    {
        JetspeedUser user = null;
        try
        {
            if (cachingEnable)
            {
                Iterator result = JetspeedSecurityCache.getRoles(username);
                if (null != result)
                {
                    return result;
                }
            }
            user = JetspeedSecurity.getUser(new UserNamePrincipal(username));
        }
        catch(JetspeedSecurityException e)
        {
            logger.error( "Failed to Retrieve User: " + username, e );
            throw new RoleException("Failed to Retrieve User: ", e);
        }
        Criteria criteria = new Criteria();
        criteria.add(TurbineUserGroupRolePeer.USER_ID, user.getUserId());
        List rels;
        HashMap roles;

        try
        {
            rels = TurbineUserGroupRolePeer.doSelect(criteria);
            if (rels.size() > 0)
            {
                roles = new HashMap(rels.size());
            }
            else
                roles = new HashMap();

            for (int ix = 0; ix < rels.size(); ix++)
            {
                TurbineUserGroupRole rel = (TurbineUserGroupRole)rels.get(ix);
                Role role = rel.getTurbineRole();
                roles.put(role.getName(), role);
            }
        }
        catch(Exception e)
        {
            logger.error( "Failed to retrieve roles ", e );
            throw new RoleException("Failed to retrieve roles ", e);
        }
        return roles.values().iterator();
    }

    /**
     * Retrieves all <code>Role</code>s.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @return Iterator over all roles.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Iterator getRoles()
        throws JetspeedSecurityException
    {
        Criteria criteria = new Criteria();
        List roles;
        try
        {
            roles = TurbineRolePeer.doSelect(criteria);
        }
        catch(Exception e)
        {
            logger.error( "Failed to retrieve roles ", e );
            throw new RoleException("Failed to retrieve roles ", e);
        }
        return roles.iterator();
    }

    /**
     * Adds a <code>Role</code> into permanent storage.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void addRole(Role role)
        throws JetspeedSecurityException
    {
        if(roleExists(role.getName()))
        {
            throw new RoleException("The role '" +
                role.getName() + "' already exists");
        }

        try
        {
            TurbineRole trole = new TurbineRole();
            trole.setRoleName(role.getName());
            Criteria criteria = TurbineRolePeer.buildCriteria(trole);
            NumberKey key = (NumberKey)TurbineRolePeer.doInsert(criteria);
            role.setId(key.toString());
        }
        catch(Exception e)
        {
            String message = "Failed to create role '" + role.getName() + "'";
            logger.error( message, e );
            throw new RoleException( message, e );
        }

        if (cachingEnable)
        {
            JetspeedSecurityCache.addRole(role);
        }

        try
        {
            addDefaultRolePSML(role);
        }
        catch (Exception e)
        {
            try
            {
                removeRole(role.getName());
            }
            catch (Exception e2)
            {
            }
            logger.error( "Failed to add default PSML for Role resource", e );
            throw new RoleException("Failed to add default PSML for Role resource", e);
        }

    }

    protected void addDefaultRolePSML(Role role)
        throws RoleException
    {
        try
        {
            JetspeedRunDataService runDataService =
               (JetspeedRunDataService)TurbineServices.getInstance()
                   .getService(RunDataService.SERVICE_NAME);
            JetspeedRunData rundata = runDataService.getCurrentRunData();
            Profile profile = Profiler.createProfile();
            profile.setRole(role);
            profile.setMediaType("html");
            Profiler.createProfile(rundata, profile);
        }
        catch (ProfileException e)
        {
            try
            {
                removeRole(role.getName());
            }
            catch(Exception e2)
            {
            }
            logger.error( "Failed to create Role PSML", e );
            throw new RoleException("Failed to create Role PSML", e);
        }
    }

    /**
     * Saves a <code>Role</code> into permanent storage.
     *
     * The security service can throw a <code>NotUniqueEntityException</code> when the public
     * credentials fail to meet the security provider-specific unique constraints.
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void saveRole(Role role)
        throws JetspeedSecurityException
    {
        if(!roleExists(role.getName()))
        {
            throw new RoleException("The role '" +
                role.getName() + "' doesn't exists");
        }

        try
        {
            if (role instanceof TurbineRole)
            {
                TurbineRolePeer.doUpdate((TurbineRole)role);
            }
            else
            {
                throw new RoleException("TurbineRoleManagment: Role is not a Turbine role, cannot update");
            }

        }
        catch(Exception e)
        {
            String message = "Failed to create role '" + role.getName() + "'";
            logger.error( message, e );
            throw new RoleException( message, e );
        }

    }

    /**
     * Removes a <code>Role</code> from the permanent store.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param rolename the principal identity of the role to be retrieved.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void removeRole(String rolename)
        throws JetspeedSecurityException
    {
        Connection conn = null;
        try
        {
            if (systemRoles.contains(rolename))
            {
                throw new RoleException("[" + rolename + "] is a system role and cannot be removed");
            }

            conn = Torque.getConnection();
            Role role = this.getRole(rolename);

            Criteria criteria = new Criteria();
            criteria.add(TurbineRolePeer.ROLE_NAME, rolename);

            if(cascadeDelete)
            {
                // CASCADE TURBINE_USER_GROUP_ROLE, TURBINE_ROLE_PERMISSION
                Criteria criteria1 = new Criteria();
                criteria1.add(TurbineUserGroupRolePeer.ROLE_ID, role.getId());
                TurbineUserGroupRolePeer.doDelete(criteria1, conn);

                Criteria criteria2 = new Criteria();
                criteria2.add(TurbineRolePermissionPeer.ROLE_ID, role.getId());
                TurbineRolePermissionPeer.doDelete(criteria2, conn);
            }

            TurbineRolePeer.doDelete(criteria, conn);
            PsmlManager.removeRoleDocuments(role);

            conn.commit();

            if (cachingEnable)
            {
                JetspeedSecurityCache.removeAllRoles(rolename);
            }
        }
        catch(Exception e)
        {
            try
            {
                conn.rollback();
            }
            catch (java.sql.SQLException sqle)
            {
                logger.error("SQLException", sqle);
            }
            String message = "Failed to remove role '" + rolename + "'";
            logger.error( message, e );
            throw new RoleException( message, e );
        }
        finally
        {
            try
            {
                Torque.closeConnection(conn);
            }
            catch (Throwable t)
            {
                logger.error( "Error closing Torque connection", t );
            }
        }

    }

    /**
     * Grants a role to a user.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void grantRole(String username, String rolename)
        throws JetspeedSecurityException
    {
        try
        {
            JetspeedUser user = JetspeedSecurity.getUser(username);
            Role role = this.getRole(rolename);

            Criteria criteria = new Criteria();
            criteria.add(TurbineUserGroupRolePeer.USER_ID, user.getUserId());
            criteria.add(TurbineUserGroupRolePeer.GROUP_ID, JetspeedSecurity.JETSPEED_GROUP_ID);
            criteria.add(TurbineUserGroupRolePeer.ROLE_ID, role.getId());
            TurbineUserGroupRolePeer.doInsert(criteria);

            if (cachingEnable)
            {
                JetspeedSecurityCache.addRole(username, role);
            }
        }
        catch(Exception e)
        {
            String message = "Grant role '" + rolename + "' to user '" + username + "' failed: ";
            logger.error( message, e );
            throw new RoleException( message, e );
        }
    }

    /**
     * Revokes a role from a user.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public void revokeRole(String username, String rolename)
        throws JetspeedSecurityException
    {
        try
        {
            JetspeedUser user = JetspeedSecurity.getUser(username);
            Role role = this.getRole(rolename);

            Criteria criteria = new Criteria();
            criteria.add(TurbineUserGroupRolePeer.USER_ID, user.getUserId());
            criteria.add(TurbineUserGroupRolePeer.GROUP_ID, JetspeedSecurity.JETSPEED_GROUP_ID);
            criteria.add(TurbineUserGroupRolePeer.ROLE_ID, role.getId());
            TurbineUserGroupRolePeer.doDelete(criteria);

            if (cachingEnable)
            {
                JetspeedSecurityCache.removeRole(username, rolename);
            }

        }
        catch(Exception e)
        {
            String message = "Revoke role '" + rolename + "' to user '" + username + "' failed: ";
            logger.error( message, e );
            throw new RoleException( message, e );
        }

    }

    /**
     * Checks for the relationship of user has a role. Returns true when the user has the given role.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @exception RoleException when the security provider has a general failure retrieving users.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public boolean hasRole(String username, String rolename)
        throws JetspeedSecurityException
    {
        List roles;

        try
        {
            if (cachingEnable)
            {
                CachedAcl acl = JetspeedSecurityCache.getAcl(username);
                if (null != acl)
                {
                    return acl.hasRole(rolename);
                }
            }
            JetspeedUser user = JetspeedSecurity.getUser(username);
            Role role = this.getRole(rolename);

            Criteria criteria = new Criteria();
            criteria.add(TurbineUserGroupRolePeer.USER_ID, user.getUserId());
            criteria.add(TurbineUserGroupRolePeer.GROUP_ID, JetspeedSecurity.JETSPEED_GROUP_ID);
            criteria.add(TurbineUserGroupRolePeer.ROLE_ID, role.getId());
            roles = TurbineUserGroupRolePeer.doSelect(criteria);

        }
        catch(Exception e)
        {
            String message = "Failed to check role '" + rolename + "'";
            logger.error( message, e );
            throw new RoleException( message, e );
        }
        return ( roles.size() > 0 );
    }


    /**
     * Retrieves a single <code>Role</code> for a given rolename principal.
     *
     * The security service may optionally check the current user context
     * to determine if the requestor has permission to perform this action.
     *
     * @param rolename a role principal identity to be retrieved.
     * @return Role the role record retrieved.
     * @exception RoleException when the security provider has a general failure.
     * @exception InsufficientPrivilegeException when the requestor is denied due to insufficient privilege
     */
    public Role getRole(String rolename)
        throws JetspeedSecurityException
    {
        List roles;
        try
        {
            Criteria criteria = new Criteria();
            criteria.add(TurbineRolePeer.ROLE_NAME, rolename);
            roles = TurbineRolePeer.doSelect(criteria);
        }
        catch(Exception e)
        {
            String message = "Failed to retrieve role '" + rolename + "'";
            logger.error( message, e );
            throw new RoleException( message, e);
        }
        if ( roles.size() > 1 )
        {
            throw new RoleException(
                "Multiple Roles with same rolename '" + rolename + "'");
        }
        if ( roles.size() == 1 )
        {
            TurbineRole role = (TurbineRole)roles.get(0);
            return role;
        }
        throw new RoleException("Unknown role '" + rolename + "'");

    }


    ///////////////////////////////////////////////////////////////////////////
    // Internal
    ///////////////////////////////////////////////////////////////////////////

    protected JetspeedRunData getRunData()
     {
         JetspeedRunData rundata = null;
         if (this.runDataService != null)
         {
             rundata = this.runDataService.getCurrentRunData();
         }
         return rundata;
     }

    /**
     * Check whether a specified role exists.
     *
     * The login name is used for looking up the account.
     *
     * @param roleName the name of the role to check for existence.
     * @return true if the specified account exists
     * @throws RoleException if there was a general db access error
     *
     */
    protected boolean roleExists(String roleName)
        throws RoleException
    {
        Criteria criteria = new Criteria();
        criteria.add(TurbineRolePeer.ROLE_NAME, roleName);
        List roles;
        try
        {
            roles = TurbineRolePeer.doSelect(criteria);
        }
        catch(Exception e)
        {
            logger.error( "Failed to check account's presence", e );
            throw new RoleException(
                "Failed to check account's presence", e);
        }
        if (roles.size() < 1)
        {
            return false;
        }
        return true;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Service Init
    ///////////////////////////////////////////////////////////////////////////


    /**
     * This is the early initialization method called by the
     * Turbine <code>Service</code> framework
     * @param conf The <code>ServletConfig</code>
     * @exception throws a <code>InitializationException</code> if the service
     * fails to initialize
     */
    public synchronized void init(ServletConfig conf)
        throws InitializationException
    {
        if (getInit()) return;

        super.init(conf);

        // get configuration parameters from Jetspeed Resources
        ResourceService serviceConf = ((TurbineServices)TurbineServices.getInstance())
                                                     .getResources(JetspeedSecurityService.SERVICE_NAME);

        this.runDataService =
           (JetspeedRunDataService)TurbineServices.getInstance()
               .getService(RunDataService.SERVICE_NAME);

        cascadeDelete = serviceConf.getBoolean( CASCADE_DELETE, DEFAULT_CASCADE_DELETE );
        cachingEnable = serviceConf.getBoolean( CACHING_ENABLE, cachingEnable );
        systemRoles = serviceConf.getVector( CONFIG_SYSTEM_ROLES, new Vector() );

        setInit(true);
     }



}


