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.ow2.jonas.webapp.jonasadmin.cmi.CmiClusterForm;

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

/**
 * CmiCluster monitoring action.
 * @author Adriana.Danes@bull.net
 */
public class CmiClusterAction extends JonasBaseAction {

    @Override
    public ActionForward executeAction(final ActionMapping mapping,
            final ActionForm form, final HttpServletRequest request,
            final HttpServletResponse response) throws IOException,
            ServletException {

        String domainName = m_WhereAreYou.getCurrentDomainName();

        // Get cluster name from the 'clust' parameter
        CmiClusterForm oForm = (CmiClusterForm) form;
        String name = request.getParameter("clust");
        if (name == null) {
            if (oForm.getName() != null) {
                name = oForm.getName();
            } else {
                addGlobalError(new Exception("CmiClusterAction: clust parameter is null."));
                saveErrors(request, m_Errors);
                return (mapping.findForward("Global Error"));
            }
        }

        oForm.setName(name);
        try {
            ObjectName on = JonasObjectName.cluster(domainName, name, "CmiCluster");
            oForm.setState(getStringAttribute(on, "State"));
            oForm.setMcastAddr(getStringAttribute(on, "McastAddr"));
            oForm.setMcastPort(getIntegerAttribute(on, "McastPort"));
            oForm.setProtocol(getStringAttribute(on, "Protocol"));
            oForm.setDelayToRefresh(getIntegerAttribute(on, "DelayToRefresh"));
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(request, m_Errors);
            return (mapping.findForward("Global Error"));
        }

        // Forward to the jsp.
        return (mapping.findForward("CmiCluster"));
    }
}
