/*
 * JBoss, the OpenSource WebOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.web.loadbalancer;

import java.io.IOException;
import javax.management.ObjectName;
import javax.servlet.ServletException;

import org.jboss.mx.util.MBeanProxyExt;
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.web.loadbalancer.scheduler.NoHostAvailableException;
import org.jboss.web.loadbalancer.scheduler.SchedulerMBean;
import org.jboss.web.loadbalancer.util.Request;
import org.w3c.dom.Element;

/**
 *
 * @jmx:mbean name="jboss.web.loadbalancer: service=Loadbalancer"
 *            extends="org.jboss.system.ServiceMBean"
 *
 * @author Thomas Peuss <jboss@peuss.de>
 * @version $Revision: 1.4 $
 */
public class LoadbalancerService
    extends ServiceMBeanSupport
    implements LoadbalancerServiceMBean
{
  protected Element config;
  protected Loadbalancer loadbalancer;
  protected ObjectName schedulerObjectName;
  protected SchedulerMBean scheduler;
  protected int timeout = 20000;

  protected void startService() throws java.lang.Exception
  {
    scheduler = (SchedulerMBean)
        MBeanProxyExt.create(SchedulerMBean.class,
                             schedulerObjectName);
    loadbalancer = new Loadbalancer(scheduler, timeout);
  }

  protected void destroyService() throws java.lang.Exception
  {
    loadbalancer = null;
  }

  /**
   * Set the scheduler for this Loadbalancer.
   * @jmx:managed-attribute
   * @param schedulerObjectName
   */
  public void setScheduler(ObjectName schedulerObjectName)
  {
    this.schedulerObjectName = schedulerObjectName;
  }

  /**
   * Get the scheduler for this Loadbalancer.
   * @jmx:managed-attribute
   */
  public ObjectName getScheduler()
  {
    return schedulerObjectName;
  }

  /**
   * Get the currently used connection timeout to slave hosts.
   * @jmx:managed-attribute
   */
  public int getConnectionTimeout()
  {
    return timeout;
  }

  /**
   * Set the currently used connection timeout to slave hosts.
   * @jmx:managed-attribute
   */
  public void setConnectionTimeout(int newTimeout)
  {
    this.timeout = newTimeout;
    if (loadbalancer != null)
    {
      loadbalancer.setConnectionTimeout(newTimeout);
    }
  }

  /**
   * Get the currently used connections to slave hosts.
   * @jmx:managed-attribute
   */
  public int getConnectionsInUse()
  {
    return loadbalancer.getConnectionsInUse();
  }

  /**
   * @jmx:managed-operation
   */
  public void createMethod(Request schedRequest) throws NoHostAvailableException
  {
    loadbalancer.createMethod(schedRequest);
  }

  /**
   * @jmx:managed-operation
   */
  public void addRequestData(Request schedRequest)
  {
    loadbalancer.addRequestData(schedRequest);
  }

  /**
   * @jmx:managed-operation
   */
  public void handleRequest(Request schedRequest) throws ServletException, IOException
  {
    loadbalancer.handleRequest(schedRequest);
  }
}