/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.webapp.jonasadmin.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectweb.jonas.jmx.CatalinaObjectName;
import org.objectweb.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.objectweb.jonas.webapp.jonasadmin.WhereAreYou;

/**
 * @author Michel-Ange ANTON
 */

public class ListRealmsAction extends BaseMemoryRealmAction {

// --------------------------------------------------------- Public Methods

    public ActionForward executeAction(ActionMapping p_Mapping, ActionForm p_Form
        , HttpServletRequest p_Request, HttpServletResponse p_Response)
        throws IOException, ServletException {

    	WhereAreYou oWhere = (WhereAreYou) p_Request.getSession().getAttribute(WhereAreYou.
                SESSION_NAME);
        String serverName = oWhere.getCurrentJonasServerName();

        // Realms to list
        String sTypeRealm = p_Request.getParameter("realm");
        if (sTypeRealm == null) {
            sTypeRealm = (String) m_Session.getAttribute("typeRealm");
        } else {
            m_Session.setAttribute("typeRealm", sTypeRealm);
        }
        // Force view all realm if null
        if (sTypeRealm == null) {
            sTypeRealm = "all";
            m_Session.setAttribute("typeRealm", sTypeRealm);
        }

        // Populate list
        try {
            String sSecurityRealmUsed = null;
            // Detect realm used by the security service
            if (m_WhereAreYou.isCatalinaServer()) {
                try {
                    // Object name used Realm
                    ObjectName oObjectName = CatalinaObjectName.catalinaRealm(m_WhereAreYou.getCurrentCatalinaDomainName());
                    // Populate
                    sSecurityRealmUsed = getStringAttribute(oObjectName, "resourceName");
                } catch (Exception e) {
                    // no action
                    // Exception because catalina realm don't exists
                }
            }

            ArrayList alRealms = new ArrayList();
            // Detect the realm type
            if (sTypeRealm.equals("all")) {
                // all Realms
                addRealmItem(alRealms, "memory", sSecurityRealmUsed, serverName);
                addRealmItem(alRealms, "datasource", sSecurityRealmUsed, serverName);
                addRealmItem(alRealms, "ldap", sSecurityRealmUsed, serverName);
                // Force the node selected in tree
                m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER)
                    + WhereAreYou.NODE_SEPARATOR + "security", true);
            }
            // Memory realm factories
            else if (sTypeRealm.equals("memory")) {
                addRealmItem(alRealms, "memory", sSecurityRealmUsed, serverName);
                // Force the node selected in tree
                m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER)
                    + WhereAreYou.NODE_SEPARATOR + "security" + WhereAreYou.NODE_SEPARATOR
                    + "factory.memory", true);
            }
            // Datasource realm factories
            else if (sTypeRealm.equals("datasource")) {
                addRealmItem(alRealms, "datasource", sSecurityRealmUsed, serverName);
                // Force the node selected in tree
                m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER)
                    + WhereAreYou.NODE_SEPARATOR + "security" + WhereAreYou.NODE_SEPARATOR
                    + "factory.datasource", true);
            }
            // Ldap realm factories
            else if (sTypeRealm.equals("ldap")) {
                addRealmItem(alRealms, "ldap", sSecurityRealmUsed, serverName);
                // Force the node selected in tree
                m_WhereAreYou.selectNameNode(getTreeBranchName(DEPTH_SERVER)
                    + WhereAreYou.NODE_SEPARATOR + "security" + WhereAreYou.NODE_SEPARATOR
                    + "factory.ldap", true);
            }
            // Unknown
            else {
                String sMess = m_Resources.getMessage("error.security.factory.realms.type.unknown"
                    , sTypeRealm);
                throw new Exception(sMess);
            }
            // Sort
            Collections.sort(alRealms, new RealmItemByNameComparator());
            // Send list to display
            m_Session.setAttribute("listRealms", alRealms);

        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // Forward to the jsp.
        return (p_Mapping.findForward("Realms"));
    }

// --------------------------------------------------------- Protected Methods
    /**
     * Add <code>RealmItem</code> in the list.
     *
     * @param p_Realms List to add found items
     * @param p_Type Type item to add (memory or datasource or ldap)
     * @param p_SecurityRealmUsed Name of realm used by the security service
     * or null if nothing used
     * @throws Exception
     */
    protected void addRealmItem(ArrayList p_Realms, String p_Type, String p_SecurityRealmUsed, String serverName)
        throws Exception {

        ArrayList al = null;

        // Memory realm factories
        if (p_Type.equals("memory")) {
            al = JonasAdminJmx.getSecurityMemoryFactories(serverName);
        }
        // Datasource realm factories
        else if (p_Type.equals("datasource")) {
            al = JonasAdminJmx.getSecurityDatasourceFactories(serverName);
        }
        // Ldap realm factories
        else if (p_Type.equals("ldap")) {
            al = JonasAdminJmx.getSecurityLdapFactories(serverName);
        }
        // Add
        if (al != null) {
            for (int i = 0; i < al.size(); i++) {
                if (p_SecurityRealmUsed != null) {
                    p_Realms.add(new RealmItem(al.get(i).toString(), p_Type
                        , p_SecurityRealmUsed.equals(al.get(i).toString())));
                } else {
                    p_Realms.add(new RealmItem(al.get(i).toString(), p_Type));
                }
            }
        }
    }
}
