/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.system;

/**
 * 
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public abstract class ServiceSupport extends ComponentSupport implements Service {


  public ServiceSupport() {
    super();
  }

  public ServiceSupport(String name) {
    super(name);
  }

  public boolean isRunning() {
    return state == State.STARTED || state == State.STARTING;
  }

  public void start() throws Exception {
    if(!State.canStart(state)) {
      logger.warn(name + " can not start, state = " + state);
      return;
    }

    logger.info("starting...");

    state = State.STARTING;

    try {
      doStart();
    }
    catch (Exception e) {
      state = State.INTERRUPTED;
      logger.error("starting failed", e);
      throw e;
    }
    state = State.STARTED;
    logger.info("started.");
  }

  public void stop() throws Exception {
    if(!State.canStop(state)) {
      logger.warn(name + " can not stop, state = " + state);
      return;
    }

    logger.info("stopping...");

    state = State.STOPPING;

    try {
      doStop();
    }
    catch (Exception e) {
      state = State.INTERRUPTED;
      logger.error("stopping failed", e);
      throw e;
    }
    state = State.STOPPED;
    logger.info("stopped");

  }

  /**
   * do actually start action
   */
  protected abstract void doStart() throws Exception;
  /**
   * do actually stop action
   */
  protected abstract void doStop() throws Exception;

}