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
 * %%
 * Copyright (C) 2008 - 2024 Code Lutin, Ultreia.io
 * %%
 * 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.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.nuiton.jaxx.runtime.swing.application.event.ApplicationRunnerEvent;
import org.nuiton.jaxx.runtime.swing.application.event.ApplicationRunnerListener;

import java.util.Objects;

/**
 * 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 Logger log = LogManager.getLogger(ApplicationRunner.class);

    private static final Object lock = new Object();

    private static ApplicationRunner runner;
    /** arguments given to runner at launch time */
    protected final String[] args;
    /** the runner to start application */
    protected final Runnable runnable;
    /** flag to reload the runner when closing it */
    protected boolean reload;
    /**
     * flag to know if application was init once.
     */
    protected boolean initOnce;
    protected long startingTime;
    protected Exception error;
    protected Thread mainThread;

    private ApplicationRunnerListener mainListener;

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

        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 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();
        }
    }

    public void setMainListener(ApplicationRunnerListener mainListener) {
        this.mainListener = Objects.requireNonNull(mainListener);
    }

    public final void launch() {
        if (mainListener == null) {
            throw new IllegalStateException("No main listener registered in ApplicationRunner");
        }
        // Default behaviour is not to reload.
        reload = false;

        if (!initOnce) {
            // only once init
            try {
                initOnce();
            } finally {
                initOnce = true;
            }
        }
        // init main thread
        mainThread = new Thread(runnable, getClass().getSimpleName());
        // start main thread
        mainThread.start();
        try {
            // Waiting for unlock
            lock();
            log.info(String.format("Application [%s] is closing...", mainThread));
        } catch (InterruptedException e) {
            log.error(String.format("%s was interrupted for reason %s", mainThread, e.getMessage()), e);
        } finally {
            close();
        }
    }

    /**
     * To execute some code only once.
     * 

* This code will not be re-execute when reloading the runner. */ public void initOnce() { mainListener.initOnce(new ApplicationRunnerEvent(this)); } /** * Hook to init runner. * * @throws Exception if any problem */ public void onInit() throws Exception { mainListener.init(new ApplicationRunnerEvent(this)); } /** * Hook to start runner. * * @throws Exception if any problem */ public void onStart() throws Exception { mainListener.start(new ApplicationRunnerEvent(this)); } /** * Hook to close runner. * * @param reload if reload was asked * @throws Exception if any problem */ public void onClose(boolean reload) throws Exception { mainListener.close(new ApplicationRunnerEvent(this, reload)); } /** * Hook to shutdown launcher * * @throws Exception if any problem */ public void onShutdown() throws Exception { mainListener.shutdown(new ApplicationRunnerEvent(this)); } /** * Hook to shutdown launcher when an exception occurs on closing. * * @param ex the error catch while closing launcher */ public void onShutdown(Exception ex) { mainListener.shutdownWithError(new ApplicationRunnerEvent(this, ex)); } /** * Hook when an error occurs in runner. * * @param e the error catch */ public void onError(Exception e) { mainListener.error(new ApplicationRunnerEvent(this, e)); } public boolean isReload() { return reload; } public void setReload(boolean reload) { this.reload = reload; } public String[] getArgs() { return args; } public final void close() { boolean doReload = isReload(); try { // close runner onClose(doReload); if (doReload) { // restart runner log.info("Will reload application"); System.runFinalization(); launch(); } } catch (Exception e) { onError(e); } finally { if (!doReload) { log.debug("Will shutdown application ..."); unlock(); // force to shutdown Runtime.getRuntime().exit(0); } } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy