/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/urm/org/apache/slide/urm/accesscontroler/impl/URMAclAdministratorImpl.java,v 1.4 2005/03/02 10:53:32 eckehard Exp $
 * $Revision: 1.4 $
 * $Date: 2005/03/02 10:53:32 $
 *
 * ====================================================================
 *
 * 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.
 */

/**
 * @author eckehard.hermann@softwareag.com
 * @author dieter.kessler@softwareag.com
 * @author zsolt.sasvarie@softwareag.com
 */

package org.apache.slide.urm.accesscontroler.impl;

import java.util.List;
import java.util.Properties;
import java.util.Set;

import com.softwareag.tamino.db.api.accessor.TXMLObjectAccessor;
import com.softwareag.tamino.db.api.connection.TLocalTransaction;
import org.apache.slide.urm.accesscontroler.URMAccessControlerSpi;
import org.apache.slide.urm.accesscontroler.URMAcl;
import org.apache.slide.urm.accesscontroler.URMAclAdministrator;
import org.apache.slide.urm.accesscontroler.URMAclIdNotUniqueException;
import org.apache.slide.urm.accesscontroler.URMAction;
import org.apache.slide.urm.accesscontroler.URMActionIdNotUniqueException;
import org.apache.slide.urm.accesscontroler.URMActionInUseException;
import org.apache.slide.urm.authenticator.URMDBTransactionException;
import org.apache.slide.urm.authenticator.URMSubject;
import org.apache.slide.urm.common.URMCloseConnectionException;
import org.apache.slide.urm.common.URMConfigurationException;
import org.apache.slide.urm.common.URMConfigurator;
import org.apache.slide.urm.common.URMConnectionException;
import org.apache.slide.urm.common.URMConstants;
import org.apache.slide.urm.common.URMDeleteException;
import org.apache.slide.urm.common.URMInsertException;
import org.apache.slide.urm.common.URMInternalServerException;
import org.apache.slide.urm.common.URMParameterException;
import org.apache.slide.urm.common.URMPrincipal;
import org.apache.slide.urm.utils.URMClassInstantiator;
import org.apache.slide.urm.utils.messagelogger.MessageLogger;
import java.util.Map;
import org.apache.slide.urm.accesscontroler.URMSemantic;
import org.apache.slide.urm.accesscontroler.URMAccessCheckException;
import org.apache.slide.urm.authenticator.rolemanager.URMRoleManagerSpi;
import org.apache.slide.urm.authenticator.userdb.URMMetadataPropsSpi;
import org.apache.slide.urm.URMException;

public class URMAclAdministratorImpl implements URMAclAdministrator {

    private static org.apache.log4j.Logger msLogger =
        org.apache.log4j.Logger.getLogger(URMAclAdministratorImpl.class.getName());
        
    private URMAccessControlerSpi mAccessControlerSpi = null;
    protected URMRoleManagerSpi mRoleManagerSpi = null;
    protected URMMetadataPropsSpi mMetadataPropsSpi = null;
    
    private String mDatabaseUri = null;
    private TXMLObjectAccessor mObjectAccessor = null;
    private TLocalTransaction mLocalTransaction = null;
    private URMSemantic mSemantic = null;
    private Object mOwner = null;

    public URMMetadataPropsSpi getMetaDataprops() {
        return mMetadataPropsSpi;
    }
    public URMAccessControlerSpi getAccessControler(){
        return mAccessControlerSpi;
    }

    public URMRoleManagerSpi getRoleManager() {
        return mRoleManagerSpi;
    }
    
    public URMAclAdministratorImpl(URMConfigurator adminConf,
                                   String username, char[] password, String domain, Object owner)
            throws URMConfigurationException {
        
        // Create the RoleManagerSpi
        
        URMConfigurator conf = (URMConfigurator)adminConf.getSubConfigurators().get("RoleManager");
        Properties props = conf.getProperties();
        String class_name = props != null ? (String)props.get(
                                        URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME) : null;
        if (class_name == null)
            throw new URMConfigurationException(
                MessageLogger.getAndLogMessage(msLogger, "URMCOC0002",
                    URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME, "Administrator/RoleManager"));

        Object radmin_params[] = { conf, owner };
        try {
            mRoleManagerSpi = (URMRoleManagerSpi)URMClassInstantiator.newInstance(class_name, radmin_params);
        } catch (URMException e) {
            throw new URMConfigurationException(MessageLogger.getAndLogMessage(msLogger, "F", e));
        }

        // Create the AccessControlerSpi
        conf = (URMConfigurator)adminConf.getSubConfigurators().get("AclAdministrator");
        props = conf.getProperties();
        class_name = props != null ? (String)props.get(
                                        URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME) : null;
        if (class_name == null)
            throw new URMConfigurationException(
                MessageLogger.getAndLogMessage(msLogger, "URMCOC0002",
                    URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME, "Administrator/AclAdministrator"));

        Object racladmin_params[] = { conf, owner };
        try {
            mSemantic = URMAclValidatorImpl.getSemantic(conf);
            mAccessControlerSpi = (URMAccessControlerSpi)URMClassInstantiator.newInstance(class_name, racladmin_params);
        } catch (URMException e) {
            throw new URMConfigurationException(MessageLogger.getAndLogMessage(msLogger, "F", e));
        }

        // Create the MetaDataPropsSpi
        conf = (URMConfigurator)adminConf.getSubConfigurator("UserDatabase/MetadataProperties");
        props = conf.getProperties();
        class_name = props != null ? (String)props.get(
                                        URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME) : null;
        if (class_name == null)
            throw new URMConfigurationException(
                MessageLogger.getAndLogMessage(msLogger, "URMCOC0002",
                    URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME, "Administrator/UserDatabase/MetadataProperties"));

        Object rmetaadmin_params[] = { conf, owner };
        try {
            mMetadataPropsSpi = (URMMetadataPropsSpi)URMClassInstantiator.newInstance(class_name, rmetaadmin_params);
        } catch (URMException e) {
            throw new URMConfigurationException(MessageLogger.getAndLogMessage(msLogger, "F", e));
        }

    }
    
    public URMAclAdministratorImpl(URMConfigurator adminConf, Object owner)
            throws URMConfigurationException {
                
        // Create the RoleManagerSpi
        
        URMConfigurator conf = (URMConfigurator)adminConf.getSubConfigurators().get("RoleManager");
        Properties props = conf.getProperties();
        String class_name = props != null ? (String)props.get(
                                        URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME) : null;
        if (class_name == null)
            throw new URMConfigurationException(
                MessageLogger.getAndLogMessage(msLogger, "URMCOC0002",
                    URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME, "Administrator/RoleManager"));

        Object radmin_params[] = { conf, owner };
        try {
            mRoleManagerSpi = (URMRoleManagerSpi)URMClassInstantiator.newInstance(class_name, radmin_params);
        } catch (URMException e) {
            throw new URMConfigurationException(MessageLogger.getAndLogMessage(msLogger, "F", e));
        }

        // Create the AccessControlerSpi
        
        conf = (URMConfigurator)adminConf.getSubConfigurators().get("AclAdministrator");
        props = conf.getProperties();
        class_name = props != null ? (String)props.get(
                                        URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME) : null;
        if (class_name == null)
            throw new URMConfigurationException(
                MessageLogger.getAndLogMessage(msLogger, "URMCOC0002",
                    URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME, "Administrator/AclAdministrator"));

        Object racladmin_params[] = { conf, owner };
        try {
            mSemantic = URMAclValidatorImpl.getSemantic(conf);
            mAccessControlerSpi = (URMAccessControlerSpi)URMClassInstantiator.newInstance(class_name, racladmin_params);
        } catch (URMException e) {
            throw new URMConfigurationException(MessageLogger.getAndLogMessage(msLogger, "F", e));
        }

        // Create the MetadataPropsSpi
        
        conf = (URMConfigurator)adminConf.getSubConfigurator("UserDatabase/MetadataProperties");
        props = conf.getProperties();
        class_name = props != null ? (String)props.get(
                                        URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME) : null;
        if (class_name == null)
            throw new URMConfigurationException(
                MessageLogger.getAndLogMessage(msLogger, "URMCOC0002",
                    URMConstants.FACTORY_CLASS_ATTRIBUTE_NAME, "Administrator/UserDatabase/MetadataProperties"));

        Object rmetaadmin_params[] = { conf, owner };
        try {
            mMetadataPropsSpi = (URMMetadataPropsSpi)URMClassInstantiator.newInstance(class_name, rmetaadmin_params);
        } catch (URMException e) {
            throw new URMConfigurationException(MessageLogger.getAndLogMessage(msLogger, "F", e));
        }
    }
        
    public URMAclAdministratorImpl(URMAclAdministrator inAdmin, Object owner) throws URMConnectionException {
        mOwner = owner;
        mAccessControlerSpi = inAdmin.getAccessControler().duplicateObject(owner);
        mRoleManagerSpi = inAdmin.getRoleManager().duplicateObject(owner);
        mMetadataPropsSpi = inAdmin.getMetaDataprops().duplicateObject(owner);
    }
    
    public URMAclAdministratorImpl(URMAclAdministrator inAdmin) throws URMConnectionException {
        mOwner = inAdmin.getOwner();
        mRoleManagerSpi = inAdmin.getRoleManager();
        mAccessControlerSpi = inAdmin.getAccessControler();
        mMetadataPropsSpi = inAdmin.getMetaDataprops();
    }
    
    public URMAcl getAcl(String id) throws URMInternalServerException {
        return mAccessControlerSpi.getAcl(id);
    }


    public List getAclPath(List acls)
        throws URMInternalServerException {
        return mAccessControlerSpi.getAclPath(acls);
    }


//    public void deleteAcl(URMAcl acl) {
//        mAccessControlerSpi.deleteAcl(acl.getId());
//    }


    public String createAcl(String id, URMSubject owner, boolean inheritable)
            throws URMAclIdNotUniqueException, URMInternalServerException, URMInsertException {

        id = mAccessControlerSpi.createAcl(id, owner.getName(), owner.getType(), owner.getDomain(), inheritable);
        return id;
    }


    public void deleteAcl(String id) throws URMInternalServerException, URMDeleteException {
        mAccessControlerSpi.deleteAcl(id);
    }

    public URMAction createAction(String name)
        throws URMActionIdNotUniqueException, URMInsertException, URMInternalServerException {
        if (name.equals(URMConstants.URM_ALL_ACTION)) throw new URMInsertException (MessageLogger.getAndLogMessage(msLogger, "URMTRC0009"));
        return mAccessControlerSpi.createAction(name);
    }

    public void deleteAction(String name) throws URMActionInUseException, URMInternalServerException, URMDeleteException{
        if (name.equals(URMConstants.URM_ALL_ACTION)) throw new URMDeleteException (MessageLogger.getAndLogMessage(msLogger, "URMTRC0007"));
        mAccessControlerSpi.deleteAction(name);
    }

    public URMAction getAction(String name)
        throws URMInternalServerException {
        if (name.equals(URMConstants.URM_ALL_ACTION)) return new URMAllActionImpl(mAccessControlerSpi);
        return mAccessControlerSpi.getAction(name);
    }
    
    /** Returns an Set of all defined URMActions
     *
     * @return Set, Set of URMActions
     */
    public Set getAllActions()
        throws URMInternalServerException {
        Set result = mAccessControlerSpi.getAllActions();
        return result;
    }
    
    public Set userWithPermissionReport(URMPrincipal princ, String action, List resource) throws URMInternalServerException
    {
        return mSemantic.userWithPermissionReport(princ, action, resource);
    }

    public Map subjectPermissionSetReport(URMPrincipal principal, URMSubject subject, List resource)
        throws URMAccessCheckException
    {
        return mSemantic.subjectPermissionSetReport(principal, subject, resource);
    }
    
    public int subjectPermissionReport(URMPrincipal principal, URMSubject subject, List resource, String action)
        throws URMAccessCheckException
    {
        return mSemantic.subjectPermissionReport(principal, subject, resource, action);
    }

    public void close() throws URMCloseConnectionException {
        /*/try {
            mConnection.close();
        } catch (TConnectionCloseException e) {
            throw new URMCloseConnectionException(msLogger, "F", e);
        }
        mConnection = null;*/
    }
    public List getAclsWithSpecificAction(List resources,
                                             List inActions)
        throws URMInternalServerException {
        return mAccessControlerSpi.getAclsWithSpecificAction(resources, inActions);
    }

    public Object getOwner() {
        return mOwner;
    }
    
    public void loadActions(Set actions) throws URMInternalServerException {
        mAccessControlerSpi.loadActionSetIntoCache(actions);
    }
    
    public void beginTransaction() throws URMDBTransactionException, URMInternalServerException {
        mAccessControlerSpi.beginTransaction();
    }

    public void endTransaction(boolean manner) throws URMDBTransactionException, URMInternalServerException {
        mRoleManagerSpi.endTransaction(manner);
        // and clear all caches
        mAccessControlerSpi.endTransaction(manner);
        mMetadataPropsSpi.endTransaction(manner);
    }
    
    /**
     * Signals the cache that an ACL does not exist
     */
    public void addTransientEmptyAcl (String aclId) {
        mAccessControlerSpi.addTransientEmptyAcl(aclId);
    }
}



