/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.system;

import org.jfox.framework.extra.Servicable;

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

public abstract class AbstractService extends AbstractComponent implements Servicable, Runnable {


    public AbstractService() {
        super();
    }

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

    public boolean isStarted() {
        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;

}
