All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.nuiton.jaxx.runtime.swing.application.ApplicationRunner Maven / Gradle / Ivy

The newest version!
/*
 * #%L
 * JAXX :: Runtime Swing Applicaiton
 * %%
 * Copyright (C) 2008 - 2017 CodeLutin
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public 
 * License along with this program.  If not, see
 * .
 * #L%
 */
package org.nuiton.jaxx.runtime.swing.application;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Simple application runner which authorize to reload an application.
 *
 * @author Tony Chemit - [email protected]
 * @since 2.1
 */
public abstract class ApplicationRunner {

    /** Logger */
    private static final Log log = LogFactory.getLog(ApplicationRunner.class);

    private static final Object lock = new Object();

    private static ApplicationRunner runner;

    public static ApplicationRunner getRunner() {
        if (runner == null) {
            throw new IllegalStateException("No runner initialized");
        }
        return runner;
    }

    public static void lock() throws InterruptedException {
        synchronized (lock) {
            // on arrete le thread principal
            // pour rendre la main a la methode main
            lock.wait();
        }
    }

    public static void unlock() {
        synchronized (lock) {
            // on arrete le thread principal
            // pour rendre la main a la methode main
            lock.notifyAll();
        }
    }

    /** arguments given to runner at launch time */
    protected final String[] args;

    /** flag to reload the runner when closing it */
    protected boolean reload;

    /** the runner to start application */
    protected final Runnable runnable;

    protected long startingTime;

    protected Exception error;

    /**
     * To execute some code only once.
     *
     * This code will not be re-execute when reloading the runner.
     */
    protected abstract void initOnce();

    /**
     * Hook to init runner.
     *
     * @throws Exception if any problem
     */
    protected abstract void onInit() throws Exception;

    /**
     * Hook to start runner.
     *
     * @throws Exception if any problem
     */
    protected abstract void onStart() throws Exception;

    /**
     * Hook to close runner.
     *
     * @param reload if reload was asked
     * @throws Exception if any problme
     */
    protected abstract void onClose(boolean reload) throws Exception;

    /**
     * Hook to shutdown launcher
     *
     * @throws Exception if any problem
     */
    protected abstract void onShutdown() throws Exception;

    /**
     * Hook to shutdown launcher when an exception occurs on clsoing.
     *
     * @param ex the error catched while closing launcher
     */
    protected abstract void onShutdown(Exception ex);

    /**
     * Hook when an error occurs in runner.
     *
     * @param e the error catched
     */
    protected abstract void onError(Exception e);

    protected ApplicationRunner(String... args) {
        runner = this;
        this.args = args;

        initOnce();

        runnable = () -> {
            startingTime = System.nanoTime();
            try {

                onInit();

                onStart();

            } catch (Exception e) {
                error = e;
                onError(e);
                unlock();
            }
        };

        Thread shutdownHook = new Thread(() -> {
            try {

                //onClose(false);
                onShutdown();

            } catch (Exception e) {
                error = e;
                onShutdown(e);
            }
        }, "ShutDown " + getClass().getSimpleName());

        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }

    public boolean isReload() {
        return reload;
    }

    public void setReload(boolean reload) {
        this.reload = reload;
    }

    protected Thread mainThread;

    public final void launch() {

        // au demarrage le reload est toujours desactive
        reload = false;

        // preparation du thread de l'application principale
        // que l'on démarre
        mainThread = new Thread(runnable, getClass().getSimpleName());
        mainThread.start();

        try {

            // on attend que l'application se termine ou demande un redémarrage
            lock();

            // on va libérer le runner
            log.info("Application [" + mainThread + "] is closing...");

        } catch (InterruptedException e) {
            if (log.isErrorEnabled()) {
                log.error(mainThread + " was interrupted for reason " + e.getMessage(), e);
            }
        } finally {

            close();

        }
    }

    public final void close() {
        boolean doReload = isReload();

        try {

            // fermeture du runner
            onClose(doReload);

            if (doReload) {

                // redemarrage du runner

                if (log.isInfoEnabled()) {
                    log.info("Will reload application");
                }

                System.runFinalization();

                launch();
            }

        } catch (Exception e) {
            onError(e);
        } finally {
            if (!doReload) {
                if (log.isDebugEnabled()) {
                    log.debug("Will shutdown application ...");
                }

                unlock();

                // force to shutdown
                Runtime.getRuntime().exit(0);
            }
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy