package org.ow2.jonas.webapp.jonasadmin.monitoring;

import java.io.IOException;

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

import org.ow2.jonas.lib.util.JonasObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasBaseAction;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Jk cluster monitoring action
 * @author Adriana.Danes@bull.net
 */
public class JkClusterAction extends JonasBaseAction {

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

        String domainName = m_WhereAreYou.getCurrentDomainName();
        // Get cluster name from the 'clust' parameter
        String name = p_Request.getParameter("clust");
        if (name == null) {
            addGlobalError(new Exception("JkClusterAction: clust parameter is null."));
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }
        // cluster type
        String type = "JkCluster";
        // Form used
        JkClusterForm oForm = (JkClusterForm) p_Form;
        oForm.setName(name);
        try {
            ObjectName on = JonasObjectName.cluster(domainName, name, type);
            String state = getStringAttribute(on, "State");
            oForm.setState(state);
            String[] workersList = getStringArrayAttribute(on, "BalancedWorkers");
            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < workersList.length; i++) {
                if (i != 0) {
                    buf.append(',');
                }
                buf.append(workersList[i]);
            }
            oForm.setWorkers(new String(buf));
            oForm.setStickySession(getBooleanAttribute(on, "StickySession"));
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }

        // Forward to the jsp.
        return (p_Mapping.findForward("JkCluster"));
    }
}
