Example usage for java.awt EventQueue invokeLater

List of usage examples for java.awt EventQueue invokeLater

Introduction

In this page you can find the example usage for java.awt EventQueue invokeLater.

Prototype

public static void invokeLater(Runnable runnable) 

Source Link

Document

Causes runnable to have its run method called in the #isDispatchThread dispatch thread of Toolkit#getSystemEventQueue the system EventQueue .

Usage

From source file:com.barclays.dfe.fw.DFEWatcher.java

/**
 * Main entry point for application./*  w  w w  .  j  a v  a 2 s. c  o m*/
 *
 * @param args the arguments
 * @throws DFEException the DFE exception
 */

public static void main(String[] args) throws DFEException {

    Properties properties = System.getProperties();
    String usage;

    //Package pkg = org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.class.getPackage();
    //Package pkg = DFEWatcher.class.getPackage().getImplementationTitle();

    //String ver = pkg.getImplementationVersion();
    String impVer = DFEWatcher.class.getPackage().getImplementationVersion();
    String impTitle = DFEWatcher.class.getPackage().getImplementationTitle();
    String impVendor = DFEWatcher.class.getPackage().getImplementationVendor();
    String specVer = DFEWatcher.class.getPackage().getSpecificationVersion();
    String specTitle = DFEWatcher.class.getPackage().getSpecificationTitle();
    String specVendor = DFEWatcher.class.getPackage().getSpecificationVendor();

    //String ver = pkg.getImplementationVersion();

    usage = "\nProduct: " + impTitle + "\nVersion: " + impVer + "\nVendor:" + impVendor;

    System.out.println("Barclays DTU File Express (DFE) (C) 2014 - Designed and Written by Barclays GTIS");
    System.out.println(usage);

    System.out.printf("DFE is using Java Runtime Version: %s VM: %s Runtime:%s\n\n",
            properties.getProperty("java.version"), properties.getProperty("java.vm.version"),
            properties.getProperty("java.runtime.version"));

    // Run the main class here - start logging here

    // Load the config file - mandatory - should also contain the name of the XML for the props
    DFEProps.getDFEProps();

    Logger logger = LoggerFactory.getLogger(DFEWatcher.class);

    logger.debug("Thread mulitplier {}", DFEProps.DFEThreadMultipler);

    DFEShutdownGraceful gs = new DFEShutdownGraceful();

    gs.attachShutDownHook();

    // create the command line parser - this is the main entry point to detect how we want to invoke the client
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    // boolean options
    options.addOption("h", "help", false, "General Help Page - this screen!");
    options.addOption("wm", "WaitMode", false, "Run the DFE Client as a service and watched folder mode");
    options.addOption("j", "TestJython", false, "Test a Jython Script");
    options.addOption("sf", "SourceFile", false, "Test a Jython Script - Source File");
    options.addOption("tf", "TargetFile", false, "Test a Jython Script - Target File");
    options.addOption("lc", "LogConfig", false,
            "Print out the full log, system and DFE configuration for the client");
    options.addOption("v", "version", false, "Build version of this client Major.Minor.Build");
    options.addOption("jetty", "jetty", false, "Start the Jetty Server for testing");

    if (args.length == 0) {
        printUsage("DFEclient" + " (Posix)", options, System.out);
        printHelp(options);
        System.exit(0);
    }

    try {

        int argsfound = 0;

        // parse the command line arguments

        line = parser.parse(options, args, true); // Pass down all the options

        if (line.hasOption("help") && args.length == 1) {

            printUsage("DFEclient" + " (Posix)", options, System.out);
            printHelp(options);
            System.exit(0);
        }

        if (line.hasOption("jetty")) {

            LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
            StatusPrinter.print(lc); // Out put logging capability

            logger.info("System Config {} ", properties);

            //logger.info("DFE Client Config {} ",props.toString());

            Server server = new Server(Integer.parseInt(DFEProps.getDFEAdminPort()));

            ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
            context.setContextPath("/util");
            server.setHandler(context);

            context.addServlet(new ServletHolder(new DFEServlet()), "/*");
            context.addServlet(new ServletHolder(new DFEServlet("stop")), "/start/*");
            context.addServlet(new ServletHolder(new DFEServlet("start")), "/stop/*");
            context.addServlet(new ServletHolder(new DFEServlet("status")), "/status/*");

            try {
                server.start();
                server.join();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            logger.debug("Completed");

            System.exit(0);
        }

        if (line.hasOption("lc")) {

            LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
            StatusPrinter.print(lc); // Out put logging capability

            logger.info("System Config {} ", properties);
            DFEProps props = new DFEProps();
            logger.info("DFE Client Config {} ", props.toString());

            System.exit(0);
        }

        // Launch a Jython script to test the engine 
        if (line.hasOption("j")) {

            DFETransferContext DFE = new DFETransferContext();

            String sf = line.getOptionValue("sf");
            String tf = line.getOptionValue("tf");
            logger.info("System Config {} ", properties);
            DFEProps props = new DFEProps();
            logger.info("DFE Client Config {} ", props.toString());

            DFE.setDFESourceFile(sf);
            DFE.setDFETransferMode("put");
            DFE.setDFETargetFileName(tf);

            String scriptName = line.getOptionValue("j");

            argsfound++;
            logger.debug("Jython Script now executed {}", scriptName);

            DFEScriptEngine se = new DFEScriptEngine();

            int result = se.RunPython(scriptName, DFE);

            logger.debug("Result from Jython Script {}", result);

            System.exit(0);
        }

        if (line.hasOption("v")) {

            logger.info(usage);

            System.exit(0);
        }

        //
        // Call this by default - this will be the main folder watcher
        //
        if (line.hasOption("wm")) {

            // Chek the status of the hub - and fail if we dont see it TODO - something better
            try {
                DFEUtils.DFECheckHub(); // Check the hub - if we get a fauilure - we   
            } catch (Exception e) {

                System.exit(DFEProps.getDFEErrorReturnCode("DFE_HUB_ATTACH_ERROR"));
            }

            logger.info("All active propserties from DFE.properties");
            DFEProps.printActiveProperties();
            logger.info("End of Property List");

            DFETransferContext dtx = new DFETransferContext();
            DFEStatus stat = new DFEStatus();

            logger.debug("Starting watched folder mode as a service");
            argsfound++;

            try {

                // Shift the args to the left and remove -wm
                String[] newArgs;
                newArgs = new String[args.length - 1];
                int i;
                for (i = 0; i < args.length - 1; i++) {

                    newArgs[i] = args[i + 1];

                }

                // Start the jetty server if admin port is non zero
                if (Integer.parseInt(DFEProps.DFEAdminPort) != 0) {
                    // Start the Jetty server here
                    logger.info("Starting Embedded JETTY server on {} /util ", DFEProps.DFEAdminPort);

                    DFEJetty jettyServer = new DFEJetty();

                    EventQueue.invokeLater(jettyServer);

                }

                DFEScriptEngine se = new DFEScriptEngine();

                logger.info("Starting startup.py script");
                //String scriptName = DFEProps.DFEStartupScript;

                // Add the startup script location
                String scriptName = DFEProps.getDFEScriptsDir() + "//" + DFEProps.getDFEStartupScript();
                //String scriptName = "startup.py";

                dtx.setDFETransferMode("startup");
                int result = se.RunPython(scriptName, dtx);

                //int result=0;

                if (result != 0) {
                    logger.info("Startup script has terminated the application with error code {}", result);
                    System.exit(0);
                }

                logger.info("Registering startup on log");
                stat.registerStartup(true); // register the startup in log file

                logger.info("Starting watcher service");

                DFEMasterRunState.startWatcher(); // Set the state flag
                try {
                    JFileWatcherService.runWaitMode(newArgs);
                } catch (Exception e) {
                    System.out.println("Exit from watcher");
                    logger.info("Graceful exit");
                }

                logger.info("Terminating Watcher Service");
                System.exit(0);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                logger.error("Cannot start File Watcher Service: ", e);
                System.exit(-10);
            }

            logger.debug("Wait mode complete - exiting DFE Java Client");

        }

        if (line.hasOption("im")) {

            logger.debug("Interactive mode complete - exiting DFE Java Client");

        }

        if (argsfound == 0)

        {

            logger.error("Error: Unknown argument");
            printUsage("DFEclient" + " (Posix)", options, System.out);
            printHelp(options);
            System.exit(0);

            System.exit(-8);
        }

    }

    // Catch the argument parser - here - only on a start 
    catch (Exception exp) {
        logger.warn("Error in argument parsing {}", exp.toString());
        System.exit(-9);
    }

}

From source file:md.mclama.com.ModManager.java

/**
 * Launch the application./*from   w  w w. ja va2s  . co m*/
 */
public static void main(String[] args) {
    try {
        workDir = new File(ModManager.class.getProtectionDomain().getCodeSource().getLocation().toURI()
                .getPath().replace("McLauncher.jar", ""));
        System.out.println("Running McLauncher from " + workDir);
    } catch (URISyntaxException e1) {
        workDir = new File("");
        e1.printStackTrace();
    }
    //      try {
    //           // Get a file channel for the file
    //         boolean FileNotLocked=false;
    //
    //           
    //           try {
    //            FileWriter file2 = new FileWriter(System.getProperty("java.io.tmpdir") + "/McLauncher.lock");
    //            file2.write("McLauncher lock");
    //            file2.close();
    //         } catch (IOException e) {
    //            FileNotLocked=true;
    //         }
    //           
    //           File file = new File(System.getProperty("java.io.tmpdir") + "/McLauncher.lock");
    //
    //           FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    //           if(file.renameTo(file)) FileNotLocked=true;
    //           if(FileNotLocked){
    //              JOptionPane.showMessageDialog(null, "Already running McLauncher, Only one instance allowed at a time\n"
    //                  + "Is this wrong? Delete McLauncher.lock in your temp folder");
    //            System.out.println("Already running McLauncher, Only one instance allowed at a time");
    //            System.exit(0);
    //           }
    //           lock = channel.lock();
    //
    //           try {
    //               lock = channel.tryLock();
    //           } catch (OverlappingFileLockException e) {
    //           }
    //           channel.close();
    //       } catch (Exception e) {
    //       }

    //Not added because i do not want to lock people out from using McLauncher if somehow this fails.
    //      if(new File(System.getProperty("java.io.tmpdir") + "/McLauncher.lock").exists()){
    //         System.exit(0);//close this instance if McLauncher is already running.
    //      }
    //      try {
    //         FileWriter file = new FileWriter(System.getProperty("java.io.tmpdir") + "/McLauncher.lock");
    //         file.write("McLauncher one instance lock");
    //         file.close();
    //      } catch (IOException e) {
    //         System.out.println("Severe, failed to create temp lock file");
    //      }
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                con = new Console();
                con.setVisible(false);
                Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
                int x = (int) ((dimension.getWidth() - con.getWidth()) / 2);
                int y = (int) ((dimension.getHeight() - con.getHeight()) / 2);
                con.setLocation(x, y);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
                ModManager frame = new ModManager();
                frame.setResizable(false);
                frame.setVisible(true);
                Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
                int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
                int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
                frame.setLocation(x, y);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:Main.java

/**
 * Causes <code>runnable</code> to have its <code>run</code> method called
 * in the dispatch thread of {@link Toolkit#getSystemEventQueue the system
 * EventQueue} if this method is not being called from it. This will happen
 * after all pending events are processed.
 * /*  w  w w  . j  a  v a  2s  . co  m*/
 * @param runnable
 *            the <code>Runnable</code> whose <code>run</code> method should
 *            be executed synchronously on the <code>EventQueue</code>
 */
public static void invokeOnEdt(Runnable runnable) {
    boolean isEdt = EventQueue.isDispatchThread();
    if (!isEdt) {
        EventQueue.invokeLater(runnable);
    } else {
        runnable.run();
    }
}

From source file:Main.java

/**
 * Execute the specified runnable in the EDT.
 *
 * @param runnable The runnable to run in EDT.
 *//*ww  w  .  j av  a 2  s .c o m*/
public static void inEdt(Runnable runnable) {
    if (isEDT()) {
        runnable.run();
    } else {
        EventQueue.invokeLater(runnable);
    }
}

From source file:Main.java

/**
 * Causes <i>runnable.run()</i> to be executed asynchronously on the AWT event dispatching thread. This will happen
 * after all pending AWT events have been processed.
 * /*from ww w .j  ava  2s .  c  om*/
 * @param runnable The runnable object.
 */
public static void invokeLater(Runnable runnable) {
    EventQueue.invokeLater(runnable);
}

From source file:net.sf.xmm.moviemanager.MovieManager.java

public static void main(String args[]) {

    boolean sandbox = SysUtil.isRestrictedSandbox();

    // Uses this to check if the app is running in a sandbox with limited privileges
    try {/* www . ja v  a 2  s .  co  m*/
        /* Disable HTTPClient logging output */
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (java.security.AccessControlException s) {
        s.printStackTrace();
        sandbox = true;
    }

    if (!sandbox) {
        // Disables logging for cobra html renderer
        java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.OFF);

        File log4jConfigFile = FileUtil.getFile("config/log4j.properties"); //$NON-NLS-1$

        if (log4jConfigFile.isFile()) {
            PropertyConfigurator.configure(log4jConfigFile.getAbsolutePath());
        } else {
            BasicConfigurator.configure();
        }
    } else
        BasicConfigurator.configure();

    log = Logger.getRootLogger();

    // Places the Log file in the user directory (the program location)
    RollingFileAppender appndr = (RollingFileAppender) log.getAppender("FileAppender");

    String logFile = null;

    try {
        if (SysUtil.isMac() || SysUtil.isWindowsVista() || SysUtil.isWindows7())
            logFile = new File(SysUtil.getConfigDir(), "Log.txt").getAbsolutePath();
    } catch (Exception e1) {
        e1.printStackTrace();
    } finally {

        if (logFile == null)
            logFile = new File(SysUtil.getUserDir(), "Log.txt").getAbsolutePath();
    }

    if (appndr != null && appndr.getFile() == null) {
        appndr.setFile(logFile);
        appndr.activateOptions();
    }

    /* Writes the date. */
    log.debug("================================================================================"); //$NON-NLS-1$
    log.debug("Log Start: " + new Date(System.currentTimeMillis())); //$NON-NLS-1$
    log.debug("MeD's Movie Manager v" + config.sysSettings.getVersion()); //$NON-NLS-1$
    log.debug("MovieManager release:" + MovieManager.getConfig().sysSettings.getRelease() + " - "
            + "IMDb Lib release:" + IMDbLib.getRelease() + " (" + IMDbLib.getVersion() + ")");
    log.debug(SysUtil.getSystemInfo(SysUtil.getLineSeparator())); //$NON-NLS-1$

    /* Loads the config */
    if (!sandbox)
        config.loadConfig();

    // Calls the plugin startup method 
    MovieManagerStartupHandler startupHandler = MovieManager.getConfig().getStartupHandler();

    if (startupHandler != null) {
        startupHandler.startUp();
    }

    if (!sandbox) {

        if (SysUtil.isAtLeastJRE6()) {
            SysUtil.includeJarFilesInClasspath("lib/LookAndFeels/1.6");
        }

        SysUtil.includeJarFilesInClasspath("lib/LookAndFeels");
        SysUtil.includeJarFilesInClasspath("lib/drivers");

        /* Must be called before the GUI is created */
        if (SysUtil.isMac()) {
            SysUtil.includeJarFilesInClasspath("lib/mac");
            lookAndFeelManager.setupOSXLaF();
        }
    }

    movieManager = new MovieManager();
    movieManager.sandbox = sandbox;

    //       Loads the HTML templates
    templateHandler.loadHTMLTemplates();

    EventQueue.invokeLater(new Runnable() {
        public final void run() {

            try {

                /* Installs the Look&Feels */
                lookAndFeelManager.instalLAFs();

                if (!MovieManager.isApplet())
                    lookAndFeelManager.setLookAndFeel();

                log.debug("Look & Feels installed.");

                log.debug("Creating MovieManager Dialog");
                movieManager.createDialog();

                /* Starts the MovieManager. */
                MovieManager.getDialog().setUp();
                log.debug("MovieManager Dialog - setup.");

                MovieManager.getDialog().showDialog();

                /* SetUp the Application Menu for OSX */
                if (SysUtil.isMac()) {
                    LookAndFeelManager.macOSXRegistration(MovieManager.getDialog());
                }

                // Calls the plugin startup method 
                MovieManagerLoginHandler loginHandler = MovieManager.getConfig().getLoginHandler();

                if (loginHandler != null) {
                    loginHandler.loginStartUp();
                }

                log.debug("Loading Database....");

                /* Loads the database. */
                databaseHandler.loadDatabase(true);

                log.debug("Database loaded.");

                AppUpdater.handleVersionUpdate();

            } catch (Exception e) {
                log.error("Exception occured while intializing MeD's Movie Manager", e);
            }
        }
    });
}

From source file:com.googlecode.logVisualizer.LogVisualizer.java

public static void main(final String[] args) {
    if (args.length > 0 && (args[0].equals("-parse") || args[0].equals("-p")))
        LogVisualizerCLI.runCLIParsing(args);
    else/* ww w .  ja  v  a2  s  .  c o m*/
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LogVisualizer();
            }
        });
}

From source file:org.sybila.parasim.extension.projectmanager.view.robustness.RobustnessSettings.java

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override/*w ww.jav  a 2s.c  o m*/
        public void run() {
            OdeSystemNames names = new OdeSystemNames(OdeSystemFactory.getInstance().getTestingOdeSystem());
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            RobustnessSettings settings = new RobustnessSettings(new RobustnessSettingsModel() {

                @Override
                public void valuesChanged(RobustnessSettingsValues values) {
                    System.out.println("Change fired.");
                }
            }, names);
            settings.setValues(getTestValues());
            frame.add(settings);
            frame.setSize(500, 750);
            frame.setVisible(true);
        }
    });
}

From source file:ensen.controler.DBpediaLookupClient.java

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                DBpediaLookupClient lookup = new DBpediaLookupClient();
                Model m = lookup.qetEntities("Syria", "", 5);
                m.write(System.out, "RDF/XML-ABBREV");

            } catch (Exception e) {
                e.printStackTrace();//from w w  w  .j ava 2 s. c  o m
            }
        }
    });
}

From source file:Main.java

/**
 * Run the runnable in EventDispatch Thread.
 * If the current thread is EventDispatch, it will run
 * immediately otherwise it will be queued in the DispatchThread
 * The difference with VFSManager.runInAWTThread() method is that
 * this one will not wait for IO Request before being executed
 *
 * @param runnable the runnable to run - it should return something meaningful from 
 *    toString() so that we can display it in the Task Monitor.
 *//*from w w  w .  j  a v  a2  s. c  o  m*/
public static void runInDispatchThread(Runnable runnable) {
    if (EventQueue.isDispatchThread())
        runnable.run();
    else
        EventQueue.invokeLater(runnable);
}