Example usage for javax.swing SwingUtilities isEventDispatchThread

List of usage examples for javax.swing SwingUtilities isEventDispatchThread

Introduction

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

Prototype

public static boolean isEventDispatchThread() 

Source Link

Document

Returns true if the current thread is an AWT event dispatching thread.

Usage

From source file:org.fit.cssbox.scriptbox.demo.tester.ConsoleInjector.java

private static void clearStyledDocument(final StyledDocument doc) {
    if (SwingUtilities.isEventDispatchThread()) {
        clearStyledDocumentImpl(doc);/*from  w w w  .ja v  a 2s  .  com*/
    } else {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                clearStyledDocumentImpl(doc);
            }
        });
    }
}

From source file:org.genedb.jogra.plugins.TermRationaliser.java

/**
 * Populates the JLists with data from the database
 * This happens right at the start to load the rationaliser
 * and then any time the user decides to refresh the 
 * models from the database. We use two parallel threads 
 * here to fetch the terms, but will eventually implement
 * some sort of caching mechanism.// ww w  .j a v a2s. com
 */
private void initModels() {

    JograProgressBar jpb = new JograProgressBar("Loading terms from database..."); //Progress bar added for better user information    
    this.setSelectedTaxonsAndScopeLabel(jogra.getSelectedOrganismNames());

    logger.info("Are we in EDT when loading data? " + SwingUtilities.isEventDispatchThread());

    /* Loading the terms from the database */
    SwingWorker<Void, Void> worker_1 = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            try {
                long startTime = System.nanoTime();
                long endTime;
                terms = termService.getTerms(getSelectedTaxons(), getTermType());
                /* Java Collections sort is a modified mergesort guaranteeing 
                 * n log(n) performance. The question is, is it slower or faster
                 * than doing a sql order by in postgres? It appears postgres
                 * uses qsort so the 'average' performance should also be n log(n).
                 * After some experimentation, we use Java's sort here since it appeared
                 * marginally faster. */
                Collections.sort(terms);
                endTime = System.nanoTime();
                logger.info("Doing sorting in SQL (specific) took : " + (endTime - startTime) + " ns.");
                for (Term term : terms) {
                    if (isShowEVC()) { //Fetch the evidence codes for the terms if the user wants them
                        term.setEvidenceCodes(termService.getEvidenceCodes(term));
                    }
                }

            } catch (SQLException se) {
                se.printStackTrace(); //How do we process this exception?
            }
            return null;
        }

        @Override
        public void done() {
            logger.info("Finished worker 1");

        }
    };

    SwingWorker<Void, Void> worker_2 = new SwingWorker<Void, Void>() {
        @Override
        public Void doInBackground() {
            try {
                long startTime = System.nanoTime();
                long endTime;
                allTerms = termService.getAllTerms(getTermType());
                Collections.sort(allTerms);
                endTime = System.nanoTime();
                logger.info("Doing sorting in SQL (general) took : " + (endTime - startTime) + " ns.");

                for (Term term : allTerms) {
                    if (isShowEVC()) { //Fetch the evidence codes for the terms if the user wants them
                        term.setEvidenceCodes(termService.getEvidenceCodes(term));
                    }
                }

            } catch (SQLException se) {
                se.printStackTrace();
            }

            return null;
        }

        @Override
        public void done() {
            logger.info("Finished worker 2");

        }
    };

    logger.info("Inside swing worker 1 to fetch and sort the specific terms");
    writeMessage("Fetching organism-specific terms from the database...\n");
    worker_1.run();
    logger.info("Inside swing worker 2 to fetch and sort all the cv terms");
    writeMessage("Fetching all the terms in the cv from the database...\n");
    worker_2.run();

    //After the data is available...
    fromList.addAll(terms);
    toList.addAll(allTerms);
    productCountLabel.setText(String.format("Number of terms for selected organisms: %d terms found (%s)",
            terms.size(), getTermType()));
    textField.setText(""); //Re-set the editable text box     
    fromList.clearSelection(); //Clear any previous selections
    toList.clearSelection();
    fromList.repaint();
    toList.repaint();

    jpb.stop();

}

From source file:org.intermine.install.swing.ProjectEditor.java

/**
 * Change the look and feel of the application.
 *
 * @param laf The new Look and Feel information.
 *
 * @return <code>true</code> if the look and feel changed ok, <code>false</code>
 * if not.//from   w ww  .  j av  a 2  s. c  o  m
 *
 * @see <a href="http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html#dynamic">
 * The Swing Tutorial</a>
 */
public boolean changeLookAndFeel(LookAndFeelInfo laf) {
    assert SwingUtilities.isEventDispatchThread() : "Can only change L&F from event thread";

    if (laf.getName().equals(UIManager.getLookAndFeel().getName())) {
        return true;
    }

    boolean changeOk = false;
    try {
        UIManager.setLookAndFeel(laf.getClassName());
        SwingUtilities.updateComponentTreeUI(this);
        SwingUtilities.updateComponentTreeUI(modelViewerFrame);
        for (Window w : getOwnedWindows()) {
            SwingUtilities.updateComponentTreeUI(w);
        }

        changeOk = true;
    } catch (Exception e) {
        logger.error("Failed to change look and feel: " + e.getMessage());
        logger.debug("", e);

        int choice = JOptionPane.showConfirmDialog(this,
                Messages.getMessage("preferences.lookandfeel.changefailed.message", e.getMessage()),
                Messages.getMessage("preferences.lookandfeel.changefailed.title"), JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE);

        changeOk = choice == JOptionPane.OK_OPTION;
    }

    return changeOk;
}

From source file:org.jajuk.ui.views.SuggestionView.java

/**
 * Refresh local thumbs./*  w  w  w  .  j  av a  2 s.c  o m*/
 */
private void refreshLocalCollectionTabs() {
    // Display a busy panel in the mean-time
    // For some reasons, if we put that code into an invokeLater() call
    // it is executed after the next done() in next swing worker, no clue why
    // As a compromise, we only show busy label when called in EDT (not the case when the 
    // call is from an update() )
    if (SwingUtilities.isEventDispatchThread()) {
        busyLocal1.setBusy(true);
        busyLocal2.setBusy(true);
        busyLocal3.setBusy(true);
        // stop all existing busy labels before we add the new ones...
        //stopAllBusyLabels();
        tabs.setComponentAt(0, UtilGUI.getCentredPanel(busyLocal1));
        tabs.setComponentAt(1, UtilGUI.getCentredPanel(busyLocal2));
        tabs.setComponentAt(2, UtilGUI.getCentredPanel(busyLocal3));
    }
    SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>() {
        JScrollPane jsp1;
        JScrollPane jsp2;
        JScrollPane jsp3;

        @Override
        public Void doInBackground() {
            albumsPrefered = AlbumManager.getInstance()
                    .getBestOfAlbums(Conf.getBoolean(Const.CONF_OPTIONS_HIDE_UNMOUNTED), NB_BESTOF_ALBUMS);
            albumsNewest = AlbumManager.getInstance()
                    .getNewestAlbums(Conf.getBoolean(Const.CONF_OPTIONS_HIDE_UNMOUNTED), NB_BESTOF_ALBUMS);
            albumsRare = AlbumManager.getInstance().getRarelyListenAlbums(
                    Conf.getBoolean(Const.CONF_OPTIONS_HIDE_UNMOUNTED), NB_BESTOF_ALBUMS);
            refreshThumbsForLocalAlbums();
            return null;
        }

        private void refreshThumbsForLocalAlbums() {
            // Refresh thumbs for required albums
            List<Album> albums = new ArrayList<Album>(10);
            albums.addAll(albumsPrefered);
            albums.addAll(albumsNewest);
            albums.addAll(albumsRare);
            if (albums.size() > 0) {
                for (Album album : albums) {
                    // Try creating the thumbnail
                    ThumbnailManager.refreshThumbnail(album, 100);
                }
            }
        }

        @Override
        public void done() {
            jsp1 = getLocalSuggestionsPanel(SuggestionType.BEST_OF);
            jsp2 = getLocalSuggestionsPanel(SuggestionType.NEWEST);
            jsp3 = getLocalSuggestionsPanel(SuggestionType.RARE);
            busyLocal1.setBusy(false);
            busyLocal2.setBusy(false);
            busyLocal3.setBusy(false);
            tabs.setComponentAt(0, jsp1);
            tabs.setComponentAt(1, jsp2);
            tabs.setComponentAt(2, jsp3);
        }
    };
    sw.execute();
}

From source file:org.kchine.r.server.manager.ServerManager.java

public static RServices createRSsh(boolean keepAlive, String codeServerHostIp, int codeServerPort,
        Properties namingInfo, int memoryMinMegabytes, int memoryMaxMegabytes, String sshHostIp, int sshPort,
        String sshLogin, String sshPwd, String name, boolean showProgress, URL[] codeUrls, String logFile)
        throws BadSshHostException, BadSshLoginPwdException, Exception {

    if (showProgress) {
        createRSshProgressArea = new JTextArea();
        createRSshProgressBar = new JProgressBar(0, 100);
        createRSshProgressFrame = new JFrame("Create R Server via SSH");

        Runnable runnable = new Runnable() {
            public void run() {
                createRSshProgressArea.setFocusable(false);
                createRSshProgressBar.setIndeterminate(true);
                JPanel p = new JPanel(new BorderLayout());
                p.add(createRSshProgressBar, BorderLayout.SOUTH);
                p.add(new JScrollPane(createRSshProgressArea), BorderLayout.CENTER);
                createRSshProgressFrame.add(p);
                createRSshProgressFrame.pack();
                createRSshProgressFrame.setSize(300, 90);
                createRSshProgressFrame.setVisible(true);
                createRSshProgressFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                PoolUtils.locateInScreenCenter(createRSshProgressFrame);
            }//  w  w  w.  ja v a2s  .  c  o m
        };

        if (SwingUtilities.isEventDispatchThread())
            runnable.run();
        else {
            SwingUtilities.invokeLater(runnable);
        }
    }

    Connection conn = null;
    try {
        conn = new Connection(sshHostIp, sshPort);
        try {
            conn.connect();
        } catch (Exception e) {
            throw new BadSshHostException();
        }
        boolean isAuthenticated = conn.authenticateWithPassword(sshLogin, sshPwd);
        if (isAuthenticated == false)
            throw new BadSshLoginPwdException();

        InputStream is = ServerManager.class
                .getResourceAsStream("/org/kchine/r/server/manager/bootstrap/BootSsh.class");
        byte[] buffer = new byte[is.available()];
        try {
            for (int i = 0; i < buffer.length; ++i) {
                int b = is.read();
                buffer[i] = (byte) b;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        String bootstrapDir = INSTALL_DIR + "classes/org/kchine/r/server/manager/bootstrap";
        new File(bootstrapDir).mkdirs();
        RandomAccessFile raf = new RandomAccessFile(bootstrapDir + "/BootSsh.class", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();

        Session sess = null;
        try {
            sess = conn.openSession();
            sess.execCommand("mkdir -p RWorkbench/classes/org/kchine/r/server/manager/bootstrap");
            sess.waitForCondition(ChannelCondition.EXIT_STATUS, 0);
        } finally {
            try {
                if (sess != null)
                    sess.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        new SCPClient(conn).put(bootstrapDir + "/BootSsh.class",
                "RWorkbench/classes/org/kchine/r/server/manager/bootstrap");
        try {
            sess = conn.openSession();

            String command = "java -classpath RWorkbench/classes org.kchine.r.server.manager.bootstrap.BootSsh"
                    + " " + new Boolean(keepAlive) + " " + codeServerHostIp + " " + codeServerPort + " "
                    + BootSsh.propertiesToString(namingInfo) + " " + "NULL" + " " + memoryMinMegabytes + " "
                    + memoryMaxMegabytes + " " + "System.out" + " "
                    + ((name == null || name.trim().equals("")) ? BootSsh.NO_NAME : name);

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i) {
                    command = command + " " + codeUrls[i];
                }
            }

            System.out.println("createRSsh command:" + command);
            sess.execCommand(command);

            InputStream stdout = new StreamGobbler(sess.getStdout());
            final BufferedReader brOut = new BufferedReader(new InputStreamReader(stdout));

            InputStream stderr = new StreamGobbler(sess.getStderr());
            final BufferedReader brErr = new BufferedReader(new InputStreamReader(stderr));
            final StringBuffer sshOutput = new StringBuffer();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        while (true) {
                            String line = brOut.readLine();
                            if (line == null)
                                break;
                            sshOutput.append(line + "\n");
                            System.out.println(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("Out Log Thread Died");
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        while (true) {
                            String line = brErr.readLine();
                            if (line == null)
                                break;
                            System.out.println(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println("Err Log Thread Died");
                }
            }).start();

            sess.waitForCondition(ChannelCondition.EXIT_STATUS, 0);

            int eIndex = sshOutput.indexOf(BootSsh.STUB_END_MARKER);
            if (eIndex != -1) {
                int bIndex = sshOutput.indexOf(BootSsh.STUB_BEGIN_MARKER);
                String stub = sshOutput.substring(bIndex + BootSsh.STUB_BEGIN_MARKER.length(), eIndex);
                return (RServices) PoolUtils.hexToStub(stub, ServerManager.class.getClassLoader());
            } else {
                return null;
            }

        } finally {
            try {
                if (sess != null)
                    sess.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (showProgress) {
            createRSshProgressFrame.setVisible(false);
        }
    }
}

From source file:org.kchine.r.server.manager.ServerManager.java

synchronized public static RServices createRInternal(String RBinPath, boolean forceEmbedded, boolean keepAlive,
        String codeServerHostIp, int codeServerPort, Properties namingInfo, int memoryMinMegabytes,
        int memoryMaxMegabytes, String name, final boolean showProgress, URL[] codeUrls, String logFile,
        String applicationType, final Runnable rShutdownHook, String forcedIP, String mainClassName,
        boolean useCreationCallback) throws Exception {

    final JTextArea[] createRProgressArea = new JTextArea[1];
    final JProgressBar[] createRProgressBar = new JProgressBar[1];
    final JFrame[] createRProgressFrame = new JFrame[1];
    ProgessLoggerInterface progressLogger = new ProgessLoggerInterface() {
        public void logProgress(String message) {

            System.out.println(">>" + message);
            try {
                if (showProgress) {
                    createRProgressArea[0].setText(message);
                }/*from   w ww.ja  v a2 s .  c  om*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    if (showProgress) {
        createRProgressArea[0] = new JTextArea();
        createRProgressBar[0] = new JProgressBar(0, 100);
        createRProgressFrame[0] = new JFrame("Creating R Server on Local Host");

        Runnable runnable = new Runnable() {
            public void run() {

                createRProgressFrame[0].setUndecorated(true);

                JPanel p = new JPanel(new BorderLayout());
                createRProgressArea[0].setForeground(Color.white);
                createRProgressArea[0].setBackground(new Color(0x00, 0x80, 0x80));
                createRProgressArea[0]
                        .setBorder(BorderFactory.createLineBorder(new Color(0x00, 0x80, 0x80), 3));
                createRProgressArea[0].setEditable(false);
                p.setBorder(BorderFactory.createLineBorder(Color.black, 3));

                createRProgressBar[0].setForeground(Color.white);
                createRProgressBar[0].setBackground(new Color(0x00, 0x80, 0x80));
                createRProgressBar[0].setIndeterminate(true);

                p.setBackground(new Color(0x00, 0x80, 0x80));
                p.add(createRProgressBar[0], BorderLayout.SOUTH);
                p.add(createRProgressArea[0], BorderLayout.CENTER);
                createRProgressFrame[0].add(p);

                createRProgressFrame[0].pack();
                createRProgressFrame[0].setSize(600, 64);
                createRProgressFrame[0].setVisible(true);
                createRProgressFrame[0].setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

                PoolUtils.locateInScreenCenter(createRProgressFrame[0]);
            }
        };
        if (SwingUtilities.isEventDispatchThread())
            runnable.run();
        else {
            SwingUtilities.invokeLater(runnable);
        }
    }

    boolean useClassPath = (codeUrls == null || codeUrls.length == 0)
            && (applicationType == null || applicationType.equals("") || applicationType.equals("standard"));
    System.out.println("application type : " + applicationType);
    System.out.println("!! use class path : " + useClassPath);
    System.out.println("java.class.path : " + System.getProperty("java.class.path"));

    try {

        progressLogger.logProgress("Inspecting R installation..");
        new File(INSTALL_DIR).mkdir();

        String rpath = null;
        String rversion = null;
        String userrjavapath = null;
        String[] rinfo = null;

        if (RBinPath != null && !RBinPath.equals("")) {
            rinfo = getRInfo(RBinPath);
            if (rinfo == null) {
                throw new ServantCreationFailed();
            }
            rpath = rinfo[0];
            rversion = rinfo[1];
            userrjavapath = rinfo[2];
        } else if (new File(INSTALL_DIR + "R/" + EMBEDDED_R).exists()) {

            rinfo = getRInfo(INSTALL_DIR + "R/" + EMBEDDED_R + "/bin/R.exe");
            if (rinfo == null) {
                throw new ServantCreationFailed();
            }
            rpath = rinfo[0];
            rversion = rinfo[1];
            userrjavapath = rinfo[2];

            System.setProperty("use.default.libs", "true");

        } else if (!forceEmbedded) {

            String rhome = System.getenv("R_HOME");
            if (rhome == null) {
                rinfo = getRInfo(null);
            } else {
                if (!rhome.endsWith("/")) {
                    rhome = rhome + "/";
                }
                System.out.println("R_HOME is set to :" + rhome);
                rinfo = getRInfo(rhome + "bin/R");
            }

            System.out.println("+rinfo:" + rinfo + " " + Arrays.toString(rinfo));
            rpath = rinfo != null ? rinfo[0] : null;
            rversion = (rinfo != null ? rinfo[1] : "");
            userrjavapath = (rinfo != null ? rinfo[2] : "");
        }

        System.out.println("rpath:" + rpath);
        System.out.println("rversion:" + rversion);
        System.out.println("user rjava path:" + userrjavapath);
        if (rpath == null) {

            String noRCause = System.getenv("R_HOME") == null ? "R is not accessible from the command line"
                    : "Your R_HOME is invalid";
            if (isWindowsOs()) {

                int n;
                if (forceEmbedded) {
                    n = JOptionPane.OK_OPTION;
                } else {
                    n = JOptionPane.showConfirmDialog(null,
                            noRCause + "\nWould you like to use the Embedded R?", "",
                            JOptionPane.YES_NO_OPTION);
                }
                if (n == JOptionPane.OK_OPTION) {
                    String rZipFileName = null;
                    rZipFileName = "http://biocep-distrib.r-forge.r-project.org/r/" + EMBEDDED_R + ".zip";
                    URL rUrl = new URL(rZipFileName);
                    InputStream is = rUrl.openConnection().getInputStream();
                    unzip(is, INSTALL_DIR + "R/", null, BUFFER_SIZE, true, "Unzipping R..", ENTRIES_NUMBER);

                    rinfo = getRInfo(INSTALL_DIR + "R/" + EMBEDDED_R + "/bin/R.exe");
                    if (rinfo == null) {
                        throw new ServantCreationFailed();
                    }
                    rpath = rinfo[0];
                    rversion = rinfo[1];
                    userrjavapath = rinfo[2];
                    System.setProperty("use.default.libs", "true");

                } else {
                    JOptionPane.showMessageDialog(null,
                            "please add R to your System path or set R_HOME to the root Directory of your local R installation\n");
                    throw new ServantCreationFailed();
                }

            } else {
                if (showProgress) {
                    JOptionPane.showMessageDialog(null, noRCause
                            + "\nplease add R to your System path \nor set R_HOME to the root Directory of your local R installation\n");
                } else {
                    System.out.println(noRCause
                            + "\n please add R to your System path \nor set R_HOME to the root Directory of your local R installation");
                }
                throw new ServantCreationFailed();
            }

        }

        progressLogger.logProgress("R installation inspection done.");

        boolean useDefaultUserLibs = (System.getenv("BIOCEP_USE_DEFAULT_LIBS") != null
                && System.getenv("BIOCEP_USE_DEFAULT_LIBS").equalsIgnoreCase("false"))
                || (System.getProperty("use.default.libs") != null
                        && System.getProperty("use.default.libs").equalsIgnoreCase("true"));

        if (System.getProperty("use.default.libs") == null
                || System.getProperty("use.default.libs").equals("")) {
            System.setProperty("use.default.libs", new Boolean(useDefaultUserLibs).toString().toLowerCase());
        }

        if (!rpath.endsWith("/") && !rpath.endsWith("\\"))
            rpath += "/";

        String rlibs = (INSTALL_DIR + "library/"
                + rversion.substring(0, rversion.lastIndexOf(' ')).replace(' ', '-')).replace('\\', '/');
        new File(rlibs).mkdirs();

        Vector<String> envVector = new Vector<String>();
        {
            Map<String, String> osenv = System.getenv();
            String OS_PATH = osenv.get("PATH");
            if (OS_PATH == null)
                OS_PATH = osenv.get("Path");
            if (OS_PATH == null)
                OS_PATH = "";

            Map<String, String> env = new HashMap<String, String>(osenv);

            env.put("Path",
                    rpath + (isWindowsOs() ? "bin" : "lib") + System.getProperty("path.separator") + OS_PATH);
            if (sci != null && isWindowsOs()) {
                env.put("Path", sci_dll_path + System.getProperty("path.separator") + env.get("Path"));
            }

            env.put("LD_LIBRARY_PATH", rpath + (isWindowsOs() ? "bin" : "lib"));
            if (sci != null) {
                env.put("SCI", sci);
                env.put("SCIHOME", sci);
                env.put("SCI_DISABLE_TK", "1");
                env.put("SCI_JAVA_ENABLE_HEADLESS", "1");

                if (!isWindowsOs()) {
                    env.put("LD_LIBRARY_PATH",
                            sci_dll_path + System.getProperty("path.separator") + env.get("LD_LIBRARY_PATH"));
                }
            }

            env.put("R_HOME", rpath);

            String R_LIBS = null;
            if (useDefaultUserLibs) {
                R_LIBS = (System.getenv("R_LIBS") != null ? System.getenv("R_LIBS") : "");
            } else {
                R_LIBS = rlibs + System.getProperty("path.separator")
                        + (System.getenv("R_LIBS") != null ? System.getenv("R_LIBS") : "");
            }

            System.out.println("R_LIBS:" + R_LIBS);
            env.put("R_LIBS", R_LIBS);

            if (System.getenv("JDK_HOME") != null)
                env.put("JAVA_HOME", System.getenv("JDK_HOME"));

            for (String k : env.keySet()) {
                envVector.add(k + "=" + env.get(k));
            }
            System.out.println("envVector:" + envVector);
        }

        String[] requiredPackages = null;
        if (useDefaultUserLibs) {
            requiredPackages = new String[0];
        } else {
            if (isWindowsOs()) {
                requiredPackages = new String[] { "rJava", "JavaGD", "iplots", "TypeInfo", "Cairo" };
            } else {
                requiredPackages = new String[] { "rJava", "JavaGD", "iplots", "TypeInfo" };
            }
        }

        Vector<String> installLibBatch = new Vector<String>();
        installLibBatch.add("source('http://bioconductor.org/biocLite.R')");

        Vector<String> missingPackages = new Vector<String>();
        for (int i = 0; i < requiredPackages.length; ++i) {
            if (!new File(rlibs + "/" + requiredPackages[i]).exists()) {
                installLibBatch.add("biocLite('" + requiredPackages[i] + "',lib='" + rlibs + "')");
                missingPackages.add(requiredPackages[i]);
            }
        }

        progressLogger.logProgress("Installing missing packages " + missingPackages + "..\n"
                + "This doesn't alter your R installation and may take several minutes. It will be done only once");

        if (installLibBatch.size() > 1) {

            File installPackagesFile = new File(INSTALL_DIR + "installRequiredPackages.R");
            File installPackagesOutputFile = new File(INSTALL_DIR + "installRequiredPackages.Rout");

            FileWriter fw = new FileWriter(installPackagesFile);
            PrintWriter pw = new PrintWriter(fw);
            for (int i = 0; i < installLibBatch.size(); ++i) {
                pw.println(installLibBatch.elementAt(i));
            }
            fw.close();

            Vector<String> installCommand = new Vector<String>();
            installCommand.add(rpath + "bin/R");
            installCommand.add("CMD");
            installCommand.add("BATCH");
            installCommand.add("--no-save");
            installCommand.add(installPackagesFile.getAbsolutePath());
            installCommand.add(installPackagesOutputFile.getAbsolutePath());

            System.out.println(installCommand);

            final Process installProc = Runtime.getRuntime().exec(installCommand.toArray(new String[0]),
                    envVector.toArray(new String[0]));
            final Vector<String> installPrint = new Vector<String>();
            final Vector<String> installErrorPrint = new Vector<String>();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(installProc.getErrorStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            installErrorPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(
                                new InputStreamReader(installProc.getInputStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            installPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            installProc.waitFor();

            if (installPackagesOutputFile.exists()
                    && installPackagesOutputFile.lastModified() > installPackagesFile.lastModified()) {
                BufferedReader br = new BufferedReader(new FileReader(installPackagesOutputFile));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }

            Vector<String> missingLibs = new Vector<String>();

            for (int i = 0; i < requiredPackages.length; ++i) {
                if (!new File(rlibs + "/" + requiredPackages[i]).exists()) {
                    missingLibs.add(requiredPackages[i]);
                }
                /*
                 * if (getLibraryPath(requiredPackages[i], rpath, rlibs) ==
                 * null) { missingLibs.add(requiredPackages[i]); }
                 */
            }

            if (missingLibs.size() > 0) {
                System.out.println(
                        "The following packages probably couldn't be automatically installed\n" + missingLibs);
                throw new ServantCreationFailed();
            }

        }

        progressLogger.logProgress("All Required Packages Are Installed.");

        progressLogger.logProgress("Generating Bootstrap Classes..");

        String bootstrap = (INSTALL_DIR + "classes/org/kchine/r/server/manager/bootstrap").replace('\\', '/');
        System.out.println(bootstrap);
        if (!new File(bootstrap).exists())
            new File(bootstrap).mkdirs();
        InputStream is = ServerManager.class
                .getResourceAsStream("/org/kchine/r/server/manager/bootstrap/Boot.class");
        byte[] buffer = new byte[is.available()];
        try {
            for (int i = 0; i < buffer.length; ++i) {
                int b = is.read();
                buffer[i] = (byte) b;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RandomAccessFile raf = new RandomAccessFile(bootstrap + "/Boot.class", "rw");
        raf.setLength(0);
        raf.write(buffer);
        raf.close();
        progressLogger.logProgress("Bootstrap Classes Generated.");

        // ---------------------------------------

        if (!isWindowsOs() && !new File(INSTALL_DIR + "VRWorkbench.sh").exists()) {
            try {

                progressLogger.logProgress("Generating Launcher Batch..");

                String launcherFile = INSTALL_DIR + "VRWorkbench.sh";
                FileWriter fw = new FileWriter(launcherFile);
                PrintWriter pw = new PrintWriter(fw);
                pw.println("javaws http://biocep-distrib.r-forge.r-project.org/rworkbench.jnlp");
                fw.close();

                progressLogger.logProgress("Launcher Batch generated..");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // ---------------------------------------

        // String jripath = getLibraryPath("rJava", rpath, rlibs) + "jri/";
        String java_library_path = null;
        if (useDefaultUserLibs) {
            java_library_path = userrjavapath + "/jri/";
            System.out.println("jripath:" + java_library_path + "\n");
        } else {
            java_library_path = rlibs + "/rJava/jri/";
            System.out.println("jripath:" + java_library_path + "\n");
        }

        if (sci != null) {
            java_library_path += System.getProperty("path.separator") + sci_dll_path;
        }

        System.out.println("java.library.path" + java_library_path);

        String cp = null;
        if (useClassPath) {
            cp = PoolUtils.getAbsoluteClassPath();
        } else {
            cp = INSTALL_DIR + "classes";
        }

        if (sci != null) {
            if (isWindowsOs()) {
                cp = cp + System.getProperty("path.separator") + sci + "modules/javasci/jar/javasci.jar";
            } else {
                String scilabLibraryDir = INSTALL_DIR + "scilab/javasci/" + SCILAB_VERSION + "/";
                if (new File(scilabLibraryDir).exists())
                    new File(scilabLibraryDir).mkdirs();
                try {
                    PoolUtils.cacheJar(
                            new URL("http://www.biocep.net/scilab/" + SCILAB_VERSION + "/" + "javasci.jar"),
                            scilabLibraryDir, PoolUtils.LOG_PRGRESS_TO_SYSTEM_OUT, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cp = cp + System.getProperty("path.separator") + scilabLibraryDir + "javasci.jar";
            }

        }

        Vector<File> extraJarFiles = new Vector<File>();

        try {

            File[] flist = new File(INSTALL_DIR).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jar");
                }
            });
            Arrays.sort(flist);
            for (int i = 0; i < flist.length; ++i) {
                extraJarFiles.add(flist[i]);
            }

            System.out.println("Insiders Extra Jars:" + Arrays.toString(flist));

            if (System.getenv().get("BIOCEP_EXTRA_JARS_LOCATION") != null) {
                flist = new File(System.getenv().get("BIOCEP_EXTRA_JARS_LOCATION"))
                        .listFiles(new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                return name.endsWith(".jar");
                            }
                        });

                Arrays.sort(flist);
                System.out.println("Outsiders Extra Jars:" + Arrays.toString(flist));
                for (int i = 0; i < flist.length; ++i) {
                    extraJarFiles.add(flist[i]);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        ManagedServant[] servantHolder = new ManagedServant[1];
        RemoteException[] exceptionHolder = new RemoteException[1];

        CreationCallBack callBack = null;
        String listenerStub = null;

        progressLogger.logProgress("Creating R Server..");

        try {

            if (useCreationCallback) {
                callBack = new CreationCallBack(servantHolder, exceptionHolder);
                listenerStub = PoolUtils.stubToHex(callBack);
            }

            String uid = null;

            if (name != null && !name.equals("") && name.contains("%{uid}")) {
                if (uid == null)
                    uid = UUID.randomUUID().toString();
                name = PoolUtils.replaceAll(name, "%{uid}", uid);
            }

            if (logFile != null && !logFile.equals("") && logFile.contains("%{uid}")) {
                if (uid == null)
                    uid = UUID.randomUUID().toString();
                logFile = PoolUtils.replaceAll(logFile, "%{uid}", uid);
            }

            Vector<String> command = new Vector<String>();

            command.add((isWindowsOs() ? "\"" : "") + System.getProperty("java.home") + "/bin/java"
                    + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-DXms" + memoryMinMegabytes + "m"
                    + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-DXmx" + memoryMaxMegabytes + "m"
                    + (isWindowsOs() ? "\"" : ""));

            command.add("-cp");
            command.add((isWindowsOs() ? "\"" : "") + cp + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-Djava.library.path=" + java_library_path
                    + (isWindowsOs() ? "\"" : ""));

            String codeBase = "http://" + codeServerHostIp + ":" + codeServerPort + "/classes/";

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i)
                    codeBase += " " + codeUrls[i].toString();
            }

            if (extraJarFiles.size() > 0) {
                for (int i = 0; i < extraJarFiles.size(); ++i)
                    codeBase += " " + extraJarFiles.elementAt(i).toURI().toURL().toString();
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Djava.rmi.server.codebase=" + codeBase
                    + (isWindowsOs() ? "\"" : ""));
            if (keepAlive) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dpreloadall=true" + (isWindowsOs() ? "\"" : ""));
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dservantclass=server.RServantImpl"
                    + (isWindowsOs() ? "\"" : ""));

            if (name == null || name.equals("")) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dprivate=true" + (isWindowsOs() ? "\"" : ""));
            } else {
                command.add((isWindowsOs() ? "\"" : "") + "-Dname=" + name + (isWindowsOs() ? "\"" : ""));
            }

            if (useCreationCallback) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dlistener.stub=" + listenerStub
                        + (isWindowsOs() ? "\"" : ""));
            }

            if (forcedIP != null && !forcedIP.equals("")) {
                command.add((isWindowsOs() ? "\"" : "") + "-Dhost.ip.forced=" + forcedIP
                        + (isWindowsOs() ? "\"" : ""));
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dapply.sandbox=false" + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dworking.dir.root=" + INSTALL_DIR + "wdir"
                    + (isWindowsOs() ? "\"" : ""));

            command.add((isWindowsOs() ? "\"" : "") + "-Dkeepalive=" + keepAlive + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dcode.server.host=" + codeServerHostIp
                    + (isWindowsOs() ? "\"" : ""));
            command.add((isWindowsOs() ? "\"" : "") + "-Dcode.server.port=" + codeServerPort
                    + (isWindowsOs() ? "\"" : ""));

            for (int i = 0; i < namingVars.length; ++i) {
                String var = namingVars[i];
                if (namingInfo.getProperty(var) != null && !namingInfo.getProperty(var).equals("")) {
                    command.add((isWindowsOs() ? "\"" : "") + "-D" + var + "=" + namingInfo.get(var)
                            + (isWindowsOs() ? "\"" : ""));
                }
            }

            command.add((isWindowsOs() ? "\"" : "") + "-Dapplication_type="
                    + (applicationType == null ? "" : applicationType) + (isWindowsOs() ? "\"" : ""));

            if (logFile != null && !logFile.equals("")) {
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.rootCategory=DEBUG,A1,A2,A3"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A1=org.apache.log4j.ConsoleAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A1.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A1.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A2=org.kchine.rpf.RemoteAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A2.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A2.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));

                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A3=org.apache.log4j.FileAppender"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "") + "-Dlog4j.appender.A3.file=" + logFile
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A3.layout=org.apache.log4j.PatternLayout"
                        + (isWindowsOs() ? "\"" : ""));
                command.add((isWindowsOs() ? "\"" : "")
                        + "-Dlog4j.appender.A3.layout.ConversionPattern=[%-5p] - %m%n"
                        + (isWindowsOs() ? "\"" : ""));
            }

            if (useClassPath) {
                command.add(mainClassName);
            } else {
                command.add("org.kchine.r.server.manager.bootstrap.Boot");
            }

            command.add("http://" + codeServerHostIp + ":" + codeServerPort + "/classes/");

            if (codeUrls != null && codeUrls.length > 0) {
                for (int i = 0; i < codeUrls.length; ++i) {
                    command.add(codeUrls[i].toString());
                }
            }

            if (extraJarFiles.size() > 0) {
                for (int i = 0; i < extraJarFiles.size(); ++i)
                    command.add(extraJarFiles.elementAt(i).toURI().toURL().toString());
            }

            final Process proc = Runtime.getRuntime().exec(command.toArray(new String[0]),
                    envVector.toArray(new String[0]));
            if (rShutdownHook != null) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            proc.waitFor();
                            rShutdownHook.run();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            final Vector<String> outPrint = new Vector<String>();
            final Vector<String> errorPrint = new Vector<String>();

            System.out.println(" command : " + command);

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            errorPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    System.out.println();
                }
            }).start();

            new Thread(new Runnable() {
                public void run() {
                    try {
                        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            System.out.println(line);
                            outPrint.add(line);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

            if (useCreationCallback) {
                long t1 = System.currentTimeMillis();
                while (servantHolder[0] == null && exceptionHolder[0] == null) {
                    if (System.currentTimeMillis() - t1 >= SERVANT_CREATION_TIMEOUT_MILLISEC)
                        throw new ServantCreationTimeout();
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
                if (exceptionHolder[0] != null) {
                    throw exceptionHolder[0];
                }
                progressLogger.logProgress("R Server Created.");
                return (RServices) servantHolder[0];
            } else {
                return null;
            }

        } finally {
            if (callBack != null) {
                UnicastRemoteObject.unexportObject(callBack, true);
            }
        }
    } finally {
        if (showProgress) {
            createRProgressFrame[0].dispose();
        }
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static void unzip(InputStream is, String destination, NameFilter nameFilter, int bufferSize,
        boolean showProgress, String taskName, int estimatedFilesNumber) {

    destination.replace('\\', '/');
    if (!destination.endsWith("/"))
        destination = destination + "/";

    final JTextArea area = showProgress ? new JTextArea() : null;
    final JProgressBar jpb = showProgress ? new JProgressBar(0, 100) : null;
    final JFrame f = showProgress ? new JFrame(taskName) : null;

    if (showProgress) {
        Runnable runnable = new Runnable() {
            public void run() {
                area.setFocusable(false);
                jpb.setIndeterminate(true);
                JPanel p = new JPanel(new BorderLayout());
                p.add(jpb, BorderLayout.SOUTH);
                p.add(new JScrollPane(area), BorderLayout.CENTER);
                f.add(p);/* ww  w  . ja v  a2 s . co m*/
                f.pack();
                f.setSize(300, 90);
                f.setVisible(true);
                locateInScreenCenter(f);
            }
        };

        if (SwingUtilities.isEventDispatchThread())
            runnable.run();
        else {
            SwingUtilities.invokeLater(runnable);
        }
    }

    try {

        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
        int entriesNumber = 0;
        int currentPercentage = 0;
        int count;
        byte data[] = new byte[bufferSize];
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory() && (nameFilter == null || nameFilter.accept(entry.getName()))) {
                String entryName = entry.getName();
                prepareFileDirectories(destination, entryName);
                String destFN = destination + File.separator + entry.getName();

                FileOutputStream fos = new FileOutputStream(destFN);
                BufferedOutputStream dest = new BufferedOutputStream(fos, bufferSize);
                while ((count = zis.read(data, 0, bufferSize)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();

                if (showProgress) {
                    ++entriesNumber;
                    final int p = (int) (100 * entriesNumber / estimatedFilesNumber);
                    if (p > currentPercentage) {
                        currentPercentage = p;
                        final JTextArea fa = area;
                        final JProgressBar fjpb = jpb;
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                fjpb.setIndeterminate(false);
                                fjpb.setValue(p);
                                fa.setText("\n" + p + "%" + " Done ");
                            }
                        });

                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                fa.setCaretPosition(fa.getText().length());
                                fa.repaint();
                                fjpb.repaint();
                            }
                        });

                    }
                }
            }
        }
        zis.close();
        if (showProgress) {
            f.dispose();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.kchine.rpf.PoolUtils.java

public static String cacheJar(URL url, String location, int logInfo, boolean forced) throws Exception {
    final String jarName = url.toString().substring(url.toString().lastIndexOf("/") + 1);
    if (!location.endsWith("/") && !location.endsWith("\\"))
        location += "/";
    String fileName = location + jarName;
    new File(location).mkdirs();

    final JTextArea area = ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) ? new JTextArea() : null;
    final JProgressBar jpb = ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) ? new JProgressBar(0, 100) : null;
    final JFrame f = ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) ? new JFrame("copying " + jarName + " ...")
            : null;//from w w  w . ja v a 2  s.  c  om

    try {
        ResponseCache.setDefault(null);
        URLConnection urlC = null;
        Exception connectionException = null;
        for (int i = 0; i < RECONNECTION_RETRIAL_NBR; ++i) {
            try {
                urlC = url.openConnection();
                connectionException = null;
                break;
            } catch (Exception e) {
                connectionException = e;
            }
        }
        if (connectionException != null)
            throw connectionException;

        InputStream is = url.openStream();
        File file = new File(fileName);

        long urlLastModified = urlC.getLastModified();
        if (!forced) {
            boolean somethingToDo = !file.exists() || file.lastModified() < urlLastModified
                    || (file.length() != urlC.getContentLength() && !isValidJar(fileName));
            if (!somethingToDo)
                return fileName;
        }

        if ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) {

            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        f.setUndecorated(true);
                        f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                        area.setEditable(false);

                        area.setForeground(Color.white);
                        area.setBackground(new Color(0x00, 0x80, 0x80));

                        jpb.setIndeterminate(true);
                        jpb.setForeground(Color.white);
                        jpb.setBackground(new Color(0x00, 0x80, 0x80));

                        JPanel p = new JPanel(new BorderLayout());
                        p.setBorder(BorderFactory.createLineBorder(Color.black, 3));
                        p.setBackground(new Color(0x00, 0x80, 0x80));
                        p.add(jpb, BorderLayout.SOUTH);
                        p.add(area, BorderLayout.CENTER);
                        f.add(p);
                        f.pack();
                        f.setSize(300, 80);
                        locateInScreenCenter(f);
                        f.setVisible(true);
                        System.out.println("here");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };

            if (SwingUtilities.isEventDispatchThread())
                runnable.run();
            else {
                SwingUtilities.invokeLater(runnable);
            }
        }

        if ((logInfo & LOG_PRGRESS_TO_SYSTEM_OUT) != 0) {
            System.out.println("Downloading " + jarName + ":");
            System.out.print("expected:==================================================\ndone    :");
        }

        if ((logInfo & LOG_PRGRESS_TO_LOGGER) != 0) {
            log.info("Downloading " + jarName + ":");
        }

        int jarSize = urlC.getContentLength();
        int currentPercentage = 0;

        FileOutputStream fos = null;
        fos = new FileOutputStream(fileName);

        int count = 0;
        int printcounter = 0;

        byte data[] = new byte[BUFFER_SIZE];
        int co = 0;
        while ((co = is.read(data, 0, BUFFER_SIZE)) != -1) {
            fos.write(data, 0, co);

            count = count + co;
            int expected = (50 * count / jarSize);
            while (printcounter < expected) {
                if ((logInfo & LOG_PRGRESS_TO_SYSTEM_OUT) != 0) {
                    System.out.print("=");
                }
                if ((logInfo & LOG_PRGRESS_TO_LOGGER) != 0) {
                    log.info((int) (100 * count / jarSize) + "% done.");
                }

                ++printcounter;
            }

            if ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) {
                final int p = (int) (100 * count / jarSize);
                if (p > currentPercentage) {
                    currentPercentage = p;

                    final JTextArea fa = area;
                    final JProgressBar fjpb = jpb;
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            fjpb.setIndeterminate(false);
                            fjpb.setValue(p);
                            fa.setText("Copying " + jarName + " ..." + "\n" + p + "%" + " Done. ");
                        }
                    });

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            fa.setCaretPosition(fa.getText().length());
                            fa.repaint();
                            fjpb.repaint();
                        }
                    });

                }
            }

        }

        /*
         * while ((oneChar = is.read()) != -1) { fos.write(oneChar);
         * count++;
         * 
         * final int p = (int) (100 * count / jarSize); if (p >
         * currentPercentage) { System.out.print(p+" % "); currentPercentage =
         * p; if (showProgress) { final JTextArea fa = area; final
         * JProgressBar fjpb = jpb; SwingUtilities.invokeLater(new
         * Runnable() { public void run() { fjpb.setIndeterminate(false);
         * fjpb.setValue(p); fa.setText("\n" + p + "%" + " Done "); } });
         * 
         * SwingUtilities.invokeLater(new Runnable() { public void run() {
         * fa.setCaretPosition(fa.getText().length()); fa.repaint();
         * fjpb.repaint(); } }); } else { if (p%2==0) System.out.print("="); } }
         *  }
         * 
         */
        is.close();
        fos.close();

    } catch (MalformedURLException e) {
        System.err.println(e.toString());
        throw e;
    } catch (IOException e) {
        System.err.println(e.toString());

    } finally {
        if ((logInfo & LOG_PRGRESS_TO_DIALOG) != 0) {
            f.dispose();
        }
        if ((logInfo & LOG_PRGRESS_TO_SYSTEM_OUT) != 0) {
            System.out.println("\n 100% of " + jarName + " has been downloaded \n");
        }
        if ((logInfo & LOG_PRGRESS_TO_LOGGER) != 0) {
            log.info(" 100% of " + jarName + " has been downloaded");
        }
    }

    return fileName;
}

From source file:org.kontalk.view.View.java

@Override
public void update(Observable o, final Object arg) {
    if (SwingUtilities.isEventDispatchThread()) {
        this.updateOnEDT(arg);
        return;//from w  w w. ja v a  2  s . c o m
    }
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            View.this.updateOnEDT(arg);
        }
    });
}

From source file:org.languagetool.gui.LanguageToolSupport.java

private synchronized List<RuleMatch> checkText(Object caller) throws IOException {
    if (this.mustDetectLanguage) {
        mustDetectLanguage = false;/*from w ww.  ja va2 s.  c o  m*/
        if (!this.textComponent.getText().isEmpty()) {
            Language detectedLanguage = autoDetectLanguage(this.textComponent.getText());
            if (!detectedLanguage.equals(this.languageTool.getLanguage())) {
                reloadLanguageTool(detectedLanguage);
                if (SwingUtilities.isEventDispatchThread()) {
                    fireEvent(LanguageToolEvent.Type.LANGUAGE_CHANGED, caller);
                } else {
                    try {
                        SwingUtilities.invokeAndWait(
                                () -> fireEvent(LanguageToolEvent.Type.LANGUAGE_CHANGED, caller));
                    } catch (InterruptedException ex) {
                        //ignore
                    } catch (InvocationTargetException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }
    if (SwingUtilities.isEventDispatchThread()) {
        fireEvent(LanguageToolEvent.Type.CHECKING_STARTED, caller);
    } else {
        try {
            SwingUtilities.invokeAndWait(() -> fireEvent(LanguageToolEvent.Type.CHECKING_STARTED, caller));
        } catch (InterruptedException ex) {
            //ignore
        } catch (InvocationTargetException ex) {
            throw new RuntimeException(ex);
        }
    }

    long startTime = System.currentTimeMillis();
    List<RuleMatch> matches = this.languageTool.check(this.textComponent.getText());
    long elapsedTime = System.currentTimeMillis() - startTime;

    int v = check.get();
    if (v == 0) {
        if (!SwingUtilities.isEventDispatchThread()) {
            SwingUtilities.invokeLater(() -> {
                updateHighlights(matches);
                fireEvent(LanguageToolEvent.Type.CHECKING_FINISHED, caller, elapsedTime);
            });
        } else {
            updateHighlights(matches);
            fireEvent(LanguageToolEvent.Type.CHECKING_FINISHED, caller, elapsedTime);
        }
    }
    return matches;
}