Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

In this page you can find the example usage for javax.swing SwingWorker SwingWorker.

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:utybo.branchingstorytree.swing.OpenBST.java

/**
 * Launch OpenBST/*from  w  ww.  j  a v a 2 s.c  o m*/
 *
 * @param args
 *            Arguments. The first argument is the language code to be used
 */
public static void main(final String[] args) {
    // Before we do anything, setup system properties
    // First one to ensure Java 9's scaling system gets out of the way
    System.setProperty("sun.java2d.uiScale", "1.0");
    // Second one to force hardware acceleration
    System.setProperty("sun.java2d.opengl", "true");

    LOG.info("OpenBST version " + VERSION + ", part of the BST project");
    LOG.trace("[ INIT ]");
    LOG.trace("Loading language files");
    loadLang(args.length > 0 ? args[0] : null);

    LOG.trace("Applying Look and Feel");
    OpenBSTGUI.initializeLaF();
    VisualsUtils.fixTextFontScaling();

    LOG.trace("Loading scaling factor");
    Icons.loadScalingFactor();

    Splashscreen sc = Splashscreen.start();
    SwingWorker<Void, String> sw = new SwingWorker<Void, String>() {

        @Override
        protected Void doInBackground() {
            LOG.trace("Initializing JavaFX");
            publish(Lang.get("splash.init"));
            // Necessary - because we are killing Scenes all the time with WebViews in NodePanels,
            // JFX may think we just ended our application.
            // OpenBST exits with a dirty System.exit() anyway.
            Platform.setImplicitExit(false);
            // Initialize JavaFX
            new JFXPanel();
            VisualsUtils.invokeJfxAndWait(() -> {
                // Initialize the web engine
                new WebEngine();
                // Initialize a view
                new WebView();
            });

            LOG.info("Loading icons...");
            publish(Lang.get("splash.icons"));
            long timeAtIconStart = System.currentTimeMillis();
            Icons.load();
            LOG.info("Time taken to load icons : " + (System.currentTimeMillis() - timeAtIconStart) + " ms");

            LOG.info("Loading backgrounds...");
            publish(Lang.get("splash.loadbg"));
            Icons.loadBackgrounds();

            // $EXPERIMENTAL
            LOG.info("Caching backgrounds...");
            publish(Lang.get("splash.processbg"));
            IMGClient.initInternal();

            // $EXPERIMENTAL
            LOG.info("Loading internal BTS files...");
            publish(Lang.get("splash.loadinternalbst"));
            loadInternalBSTFiles();

            return null;
        }

        @Override
        protected void process(List<String> chunks) {
            String s = chunks.get(chunks.size() - 1);
            sc.setText(s);
        }

    };

    sw.execute();
    try {
        sw.get();
    } catch (InterruptedException | ExecutionException e1) {
        OpenBST.LOG.error(e1);
    }

    VisualsUtils.invokeSwingAndWait(() -> {
        sc.setText(Lang.get("splash.launch"));
        sc.lock();
        sc.stop();
    });
    LOG.trace("Launching app...");
    OpenBSTGUI.launch();

    VisualsUtils.invokeSwingAndWait(() -> sc.dispose());

    LOG.trace("Checking versions...");
    if (!"<unknown version>".equals(VERSION)) {
        SwingWorker<UpdateInfo, Void> worker = new SwingWorker<UpdateInfo, Void>() {

            @Override
            protected UpdateInfo doInBackground() throws Exception {
                URL updateInfoSite = new URL("https://utybo.github.io/BST/version.json");
                UpdateInfo info = new Gson().fromJson(
                        new InputStreamReader(updateInfoSite.openStream(), StandardCharsets.UTF_8),
                        UpdateInfo.class);
                return info;
            }

            @Override
            protected void done() {
                try {
                    UpdateInfo remoteVersion = this.get();
                    ComparableVersion remoteUnstable = new ComparableVersion(remoteVersion.unstable),
                            remoteStable = new ComparableVersion(remoteVersion.stable);
                    ComparableVersion local = new ComparableVersion(VERSION.substring(0, VERSION.length() - 1));

                    if (VERSION.endsWith("u")) {
                        // Local version is unstable
                        // Show updates to either the most recent unstable or the most recent stable
                        if (local.compareTo(remoteStable) < 0 && remoteStable.compareTo(remoteUnstable) < 0) {
                            // local (unstable) < stable < unstable
                            // Give options for both unstable and stable
                            JButton stablebtn = new JButton(Lang.get("up.moreinfostable"));
                            stablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.stableurl);
                            });
                            JButton unstablebtn = new JButton(Lang.get("up.moreinfounstable"));
                            unstablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.unstableurl);
                            });
                            OpenBSTGUI.getInstance()
                                    .addBanner(new JBannerPanel(
                                            new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                            new Color(142, 255, 159), Lang.get("up.message1"), stablebtn, false,
                                            unstablebtn));
                        } else if (remoteStable.compareTo(local) < 0 && local.compareTo(remoteUnstable) < 0) {
                            // stable < local (unstable) < unstable
                            JButton unstablebtn = new JButton(Lang.get("up.moreinfo"));
                            unstablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.unstableurl);
                            });
                            OpenBSTGUI.getInstance().addBanner(new JBannerPanel(
                                    new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                    new Color(142, 255, 159), Lang.get("up.message2"), unstablebtn, false));
                        } else if (remoteUnstable.compareTo(remoteStable) < 0
                                && local.compareTo(remoteStable) < 0) {
                            // local (unstable) < stable
                            // and unstable < stable
                            JButton stablebtn = new JButton(Lang.get("up.moreinfo"));
                            stablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.stableurl);
                            });
                            OpenBSTGUI.getInstance().addBanner(new JBannerPanel(
                                    new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                    new Color(142, 255, 159), Lang.get("up.message3"), stablebtn, false));
                        }
                    } else {
                        // If we're not running an unstable version, the only interesting case is local < stable
                        if (local.compareTo(remoteStable) < 0) {
                            // local (stable) < stable
                            JButton stablebtn = new JButton(Lang.get("up.moreinfo"));
                            stablebtn.addActionListener(e -> {
                                VisualsUtils.browse(remoteVersion.stableurl);
                            });
                            OpenBSTGUI.getInstance().addBanner(new JBannerPanel(
                                    new ImageIcon(Icons.getImage("Installing Updates", 48)),
                                    new Color(142, 255, 159), Lang.get("up.message4"), stablebtn, false));
                        }
                    }
                }

                catch (InterruptedException | ExecutionException e) {
                    LOG.warn("Failed to read update information", e);
                    JButton showDetails = new JButton(Lang.get("up.showdetails"));
                    showDetails.addActionListener(ev -> Messagers.showException(OpenBSTGUI.getInstance(),
                            Lang.get("up.failedmessage"), e));
                    OpenBSTGUI.getInstance()
                            .addBanner(new JBannerPanel(new ImageIcon(Icons.getImage("Cancel", 16)),
                                    new Color(255, 144, 144), Lang.get("up.failedbanner"), showDetails, false));
                }
            }
        };
        worker.execute();
    }
}

From source file:utybo.branchingstorytree.swing.OpenBSTGUI.java

/**
 * Load and parse a file, using appropriate dialogs if an error occurs to
 * inform the user and even give him the option to reload the file
 *
 * @param file//from   w  w w. j ava  2  s .c o m
 *            The file to load
 * @param client
 *            The BST Client. This is required for parsing the file
 * @return
 */
public void loadFile(final File file, final TabClient client, Consumer<BranchingStory> callback) {
    SwingWorker<BranchingStory, Object> worker = new SwingWorker<BranchingStory, Object>() {
        @Override
        protected BranchingStory doInBackground() throws Exception {
            try {
                LOG.trace("Parsing story");
                String ext = FilenameUtils.getExtension(file.getName());
                BranchingStory bs = null;
                if (ext.equals("bsp")) {
                    bs = BSTPackager.fromPackage(new ProgressMonitorInputStream(instance,
                            "Opening " + file.getName() + "...", new FileInputStream(file)), client);
                } else {
                    bs = parser
                            .parse(new BufferedReader(new InputStreamReader(
                                    new ProgressMonitorInputStream(instance,
                                            "Opening " + file.getName() + "...", new FileInputStream(file)),
                                    StandardCharsets.UTF_8)), new Dictionary(), client, "<main>");
                    client.setBRMHandler(new BRMFileClient(file, client, bs));
                }
                callback.accept(bs);
                return bs;
            } catch (final IOException e) {
                LOG.error("IOException caught", e);
                showException(Lang.get("file.error").replace("$e", e.getClass().getSimpleName()).replace("$m",
                        e.getMessage()), e);
                return null;
            } catch (final BSTException e) {
                LOG.error("BSTException caught", e);
                String s = "<html>" + Lang.get("file.bsterror.1");
                s += Lang.get("file.bsterror.2");
                s += Lang.get("file.bsterror.3").replace("$l", "" + e.getWhere()).replace("$f", "[main]");
                if (e.getCause() != null) {
                    s += Lang.get("file.bsterror.4").replace("$e", e.getCause().getClass().getSimpleName())
                            .replace("$m", e.getCause().getMessage());
                }
                s += Lang.get("file.bsterror.5").replace("$m", "" + e.getMessage());
                s += Lang.get("file.bsterror.6");
                String s2 = s;
                if (doAndReturn(() -> Messagers.showConfirm(instance, s2, Messagers.OPTIONS_YES_NO,
                        Messagers.TYPE_ERROR, Lang.get("bsterror"))) == Messagers.OPTION_YES) {
                    LOG.debug("Reloading");
                    return doInBackground();
                }
                return null;
            } catch (final Exception e) {
                LOG.error("Random exception caught", e);
                showException(Lang.get("file.crash"), e);
                return null;
            }

        }

        private <T> T doAndReturn(Supplier<T> supplier) {
            ArrayList<T> l = new ArrayList<>();
            invokeSwingAndWait(() -> {
                l.add(supplier.get());
            });
            return l.size() == 0 ? null : l.get(0);
        }

        @Override
        protected void done() {
            try {
                get();
            } catch (InterruptedException e) {
                // Shouldn't happen
            } catch (ExecutionException e) {
                LOG.error("Random exception caught", e);
                Messagers.showException(instance, Lang.get("file.crash"), e);
            }
        }
    };
    worker.execute();
}

From source file:xtrememp.update.SoftwareUpdate.java

public static void checkForUpdates(final boolean showDialogs) {
    checkForUpdatesWorker = new SwingWorker<Version, Void>() {

        @Override/* w  w  w. j a v a  2 s.  c o  m*/
        protected Version doInBackground() throws Exception {
            logger.debug("checkForUpdates: started...");
            long startTime = System.currentTimeMillis();
            Version version = getLastVersion(new URL(updatesURL));
            if (showDialogs) {
                // Simulate (if needed) a delay of 2 sec max to let the user cancel the task.
                long delayTime = System.currentTimeMillis() - startTime - 2000;
                if (delayTime > 0) {
                    Thread.sleep(delayTime);
                }
            }
            return version;
        }

        @Override
        protected void done() {
            logger.debug("checkForUpdates: done");
            if (checkForUpdatesDialog != null && checkForUpdatesDialog.isVisible()) {
                checkForUpdatesDialog.dispose();
            }
            if (!isCancelled()) {
                try {
                    newerVersion = get();
                    if (newerVersion != null && newerVersion.compareTo(currentVersion) == 1) {
                        logger.debug("checkForUpdates: currentVersion = {}", currentVersion);
                        logger.debug("checkForUpdates: newerVersion = {}", newerVersion);
                        logger.debug("SoftwareUpdate::checkForUpdates: updates found");
                        Object[] options = { tr("Button.Cancel") };
                        Desktop desktop = null;
                        if (Desktop.isDesktopSupported()) {
                            desktop = Desktop.getDesktop();
                            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                                options = new Object[] { tr("Button.Download"), tr("Button.Cancel") };
                            }
                        }
                        JPanel panel = new JPanel(new BorderLayout(0, 10));
                        panel.add(new JLabel("<html>" + tr("Dialog.SoftwareUpdate.UpdatesFound") + " ("
                                + newerVersion + ")</html>"), BorderLayout.CENTER);
                        JCheckBox hideCheckBox = null;
                        if (Settings.isAutomaticUpdatesEnabled()) {
                            hideCheckBox = new JCheckBox(
                                    tr("Dialog.SoftwareUpdate.DisableAutomaticCheckForUpdates"));
                            panel.add(hideCheckBox, BorderLayout.SOUTH);
                        }
                        int option = JOptionPane.showOptionDialog(XtremeMP.getInstance().getMainFrame(), panel,
                                tr("Dialog.SoftwareUpdate"), JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                        if (hideCheckBox != null) {
                            Settings.setAutomaticUpdatesEnabled(!hideCheckBox.isSelected());
                        }
                        if ((options.length == 2) && (option == JOptionPane.OK_OPTION)) {
                            try {
                                URL url = new URL(newerVersion.getDownloadURL());
                                desktop.browse(url.toURI());
                            } catch (Exception ex) {
                                logger.error(ex.getMessage(), ex);
                            }
                        }
                    } else {
                        logger.debug("checkForUpdates: no updates found");
                        if (showDialogs) {
                            JOptionPane.showMessageDialog(XtremeMP.getInstance().getMainFrame(),
                                    tr("Dialog.SoftwareUpdate.NoUpdatesFound"), tr("Dialog.SoftwareUpdate"),
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    }
                } catch (Exception ex) {
                    logger.error(ex.getMessage(), ex);
                    if (showDialogs) {
                        JOptionPane.showMessageDialog(XtremeMP.getInstance().getMainFrame(),
                                tr("Dialog.SoftwareUpdate.ConnectionFailure"), tr("Dialog.SoftwareUpdate"),
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        }
    };
    checkForUpdatesWorker.execute();
}