Example usage for javax.swing JProgressBar JProgressBar

List of usage examples for javax.swing JProgressBar JProgressBar

Introduction

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

Prototype

public JProgressBar(int min, int max) 

Source Link

Document

Creates a horizontal progress bar with the specified minimum and maximum.

Usage

From source file:net.sourceforge.squirrel_sql.client.gui.ProgressAbortDialog.java

private void createGUI() {
    JPanel dialogPanel = new JPanel(new GridBagLayout());
    dialogPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
    GridBagConstraints c;//w  ww. jav a 2s. c  om

    c = new GridBagConstraints();
    c.gridx = 0;
    c.gridy = 0;
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 0.5;
    c.anchor = GridBagConstraints.WEST;
    c.insets = new Insets(4, 0, 4, 0);
    taskDescriptionComponent = createTaskDescripion();
    dialogPanel.add(taskDescriptionComponent, c);

    c.gridy++;
    JPanel progressPanel = new JPanel(new GridBagLayout());
    progressPanel.setMinimumSize(new Dimension(400, 200));
    progressPanel.setPreferredSize(new Dimension(400, 200));
    progressPanel.setBorder(BorderFactory.createTitledBorder("Progress"));
    dialogPanel.add(progressPanel, c);

    c.gridy = 0;
    c.gridx = 0;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.0;
    c.weighty = 0.0;
    c.insets = new Insets(4, 10, 4, 10);
    statusLabel = new JLabel(i18n.INITIAL_LOADING_PREFIX);
    progressPanel.add(statusLabel, c);

    c.gridy++;
    c.insets = new Insets(4, 10, 4, 10);
    additionalStatusLabel = new JLabel(" "); // Must be a space :-)
    progressPanel.add(additionalStatusLabel, c);

    c.gridy++;
    c.weightx = 1.0;
    progressBar = new JProgressBar(0, itemCount);
    progressBar.setIndeterminate(indeterminate);
    progressPanel.add(progressBar, c);

    c.gridy++;
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
    historyArea = new JTextArea();
    historyArea.setEditable(false);
    JScrollPane jScrollPane = new JScrollPane(historyArea);
    progressPanel.add(jScrollPane, c);

    if (abortHandler != null) {
        cancelButton = new JButton(new CancelAction());

        c.gridy++;
        c.anchor = GridBagConstraints.WEST;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.0;
        c.weighty = 0.0;
        dialogPanel.add(cancelButton, c);
    }

    super.getContentPane().add(dialogPanel);
    super.pack();
    super.setSize(new Dimension(450, 450));
    super.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    super.addWindowListener(new WindowCloseListener());
}

From source file:org.gofleet.module.routing.RoutingMap.java

private void newPlan(LatLon from) {
    JDialog d = new JDialog(basicWindow.getFrame(), "Generating New Plan");
    try {//from   w ww.  j  av a 2 s . c  o m
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new RoutingFilter());
        fc.setAcceptAllFileFilterUsed(true);
        int returnVal = fc.showOpenDialog(basicWindow.getFrame());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            log.debug("Opening: " + file.getName());

            JProgressBar progressBar = new JProgressBar(0, getNumberLines(file) * 2);
            progressBar.setValue(0);
            progressBar.setPreferredSize(new Dimension(150, 50));
            progressBar.setStringPainted(true);

            d.add(progressBar);
            d.pack();
            d.setVisible(true);

            TSPPlan[] param = processFile(file, progressBar);

            Map<String, String> values = getValues(from);

            double[] origin = new double[2];
            origin[0] = new Double(values.get("origin_x"));
            origin[1] = new Double(values.get("origin_y"));

            TSPPlan[] res = calculateRouteOnWS(new Integer(values.get("maxDistance")),
                    new Integer(values.get("maxTime")), origin, new Integer(values.get("startTime")), param,
                    new Integer(values.get("timeSpentOnStop")));

            progressBar.setValue(progressBar.getMaximum() - res.length);

            processTSPPlan(res, progressBar);

        } else {
            log.trace("Open command cancelled by user.");
        }
    } catch (Throwable t) {
        log.error("Error computing new plan", t);
        JOptionPane.showMessageDialog(basicWindow.getFrame(),
                "<html><p>" + i18n.getString("Main.Error") + ":</p><p>" + t.toString() + "</p><html>",
                i18n.getString("Main.Error"), JOptionPane.ERROR_MESSAGE);
    } finally {
        d.setVisible(false);
        d.dispose();
    }

}

From source file:org.jets3t.gui.skins.SkinsFactory.java

/**
 * @param itemName//w  w w .j  a va  2  s  .  com
 * the name of this specific item in the GUI, which may be used to determine how the skinned
 * item should look or behave.
 *
 * @return
 * a <code>SkinnedJProgressBar</code> class implementation for the current skin, or a default
 * JProgressBar if no skin-specific implementation is available.
 */
public JProgressBar createSkinnedJProgressBar(String itemName, int min, int max) {
    JProgressBar jProgressBar = (JProgressBar) instantiateClass(buildSkinnedClassName("SkinnedJProgressBar"),
            itemName);
    if (jProgressBar != null) {
        jProgressBar.setMinimum(min);
        jProgressBar.setMaximum(max);
        return jProgressBar;
    } else {
        jProgressBar = new JProgressBar(min, max);
        return jProgressBar;
    }
}

From source file:org.jivesoftware.sparkimpl.plugin.viewer.PluginViewer.java

private void downloadPlugin(final PublicPlugin plugin) {
    // Prepare HTTP post
    final GetMethod post = new GetMethod(plugin.getDownloadURL());

    // Get HTTP client
    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    final HttpClient httpclient = new HttpClient();
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");

    if (Default.getBoolean("PLUGIN_REPOSITORY_USE_PROXY")) {
        if (ModelUtil.hasLength(proxyHost) && ModelUtil.hasLength(proxyPort)) {
            try {
                httpclient.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
            } catch (NumberFormatException e) {
                Log.error(e);/*  w  w w. ja  va 2s  . co  m*/
            }
        }
    }
    // Execute request

    try {
        int result = httpclient.executeMethod(post);
        if (result != 200) {
            return;
        }

        long length = post.getResponseContentLength();
        int contentLength = (int) length;

        progressBar = new JProgressBar(0, contentLength);

        final JFrame frame = new JFrame(Res.getString("message.downloading", plugin.getName()));

        frame.setIconImage(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE).getImage());

        final Thread thread = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(2000);
                    InputStream stream = post.getResponseBodyAsStream();

                    URL url = new URL(plugin.getDownloadURL());
                    String name = URLFileSystem.getFileName(url);
                    String directoryName = URLFileSystem.getName(url);

                    File pluginDownload = new File(PluginManager.PLUGINS_DIRECTORY, name);

                    FileOutputStream out = new FileOutputStream(pluginDownload);
                    copy(stream, out);
                    out.close();

                    frame.dispose();

                    // Remove SparkPlugUI
                    // Clear all selections
                    Component[] comps = availablePanel.getComponents();
                    for (Component comp : comps) {
                        if (comp instanceof SparkPlugUI) {
                            SparkPlugUI sparkPlug = (SparkPlugUI) comp;
                            if (sparkPlug.getPlugin().getDownloadURL().equals(plugin.getDownloadURL())) {
                                availablePanel.remove(sparkPlug);

                                _deactivatedPlugins.remove(sparkPlug.getPlugin().getName());
                                _prefs.setDeactivatedPlugins(_deactivatedPlugins);

                                PluginManager.getInstance().addPlugin(sparkPlug.getPlugin());

                                sparkPlug.showOperationButton();
                                installedPanel.add(sparkPlug);
                                sparkPlug.getPlugin()
                                        .setPluginDir(new File(PluginManager.PLUGINS_DIRECTORY, directoryName));
                                installedPanel.invalidate();
                                installedPanel.repaint();
                                availablePanel.invalidate();
                                availablePanel.invalidate();
                                availablePanel.validate();
                                availablePanel.repaint();
                            }
                        }
                    }
                } catch (Exception ex) {
                    // Nothing to do
                } finally {
                    // Release current connection to the connection pool once you are done
                    post.releaseConnection();
                }
            }
        });

        frame.getContentPane().setLayout(new GridBagLayout());
        frame.getContentPane().add(new JLabel(Res.getString("message.downloading.spark.plug")),
                new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
                        GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
        frame.getContentPane().add(progressBar, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
        frame.pack();
        frame.setSize(400, 100);
        GraphicUtils.centerWindowOnComponent(frame, this);

        frame.setVisible(true);
        thread.start();

    } catch (IOException e) {
        Log.error(e);
    }
}

From source file:org.jivesoftware.sparkimpl.updater.CheckUpdates.java

public void downloadUpdate(final File downloadedFile, final SparkVersion version) {
    final java.util.Timer timer = new java.util.Timer();

    // Prepare HTTP post
    final GetMethod post = new GetMethod(version.getDownloadURL());

    // Get HTTP client
    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    final HttpClient httpclient = new HttpClient();
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (ModelUtil.hasLength(proxyHost) && ModelUtil.hasLength(proxyPort)) {
        try {/*from w w  w .  j ava  2s.  c  om*/
            httpclient.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        } catch (NumberFormatException e) {
            Log.error(e);
        }
    }

    // Execute request

    try {
        int result = httpclient.executeMethod(post);
        if (result != 200) {
            return;
        }

        long length = post.getResponseContentLength();
        int contentLength = (int) length;

        bar = new JProgressBar(0, contentLength);
    } catch (IOException e) {
        Log.error(e);
    }

    final JFrame frame = new JFrame(Res.getString("title.downloading.im.client"));

    frame.setIconImage(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_IMAGE).getImage());

    titlePanel = new TitlePanel(Res.getString("title.upgrading.client"),
            Res.getString("message.version", version.getVersion()),
            SparkRes.getImageIcon(SparkRes.SEND_FILE_24x24), true);

    final Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                InputStream stream = post.getResponseBodyAsStream();
                long size = post.getResponseContentLength();
                ByteFormat formater = new ByteFormat();
                sizeText = formater.format(size);
                titlePanel.setDescription(Res.getString("message.version", version.getVersion()) + " \n"
                        + Res.getString("message.file.size", sizeText));

                downloadedFile.getParentFile().mkdirs();

                FileOutputStream out = new FileOutputStream(downloadedFile);
                copy(stream, out);
                out.close();

                if (!cancel) {
                    downloadComplete = true;
                    promptForInstallation(downloadedFile, Res.getString("title.download.complete"),
                            Res.getString("message.restart.spark"));
                } else {
                    out.close();
                    downloadedFile.delete();
                }

                UPDATING = false;
                frame.dispose();
            } catch (Exception ex) {
                // Nothing to do
            } finally {
                timer.cancel();
                // Release current connection to the connection pool once you are done
                post.releaseConnection();
            }
        }
    });

    frame.getContentPane().setLayout(new GridBagLayout());
    frame.getContentPane().add(titlePanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
    frame.getContentPane().add(bar, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));

    JEditorPane pane = new JEditorPane();
    boolean displayContentPane = version.getChangeLogURL() != null || version.getDisplayMessage() != null;

    try {
        pane.setEditable(false);
        if (version.getChangeLogURL() != null) {
            pane.setEditorKit(new HTMLEditorKit());
            pane.setPage(version.getChangeLogURL());
        } else if (version.getDisplayMessage() != null) {
            pane.setText(version.getDisplayMessage());
        }

        if (displayContentPane) {
            frame.getContentPane().add(new JScrollPane(pane), new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0,
                    GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        }
    } catch (IOException e) {
        Log.error(e);
    }

    frame.getContentPane().setBackground(Color.WHITE);
    frame.pack();
    if (displayContentPane) {
        frame.setSize(600, 400);
    } else {
        frame.setSize(400, 100);
    }
    frame.setLocationRelativeTo(SparkManager.getMainWindow());
    GraphicUtils.centerWindowOnScreen(frame);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent windowEvent) {
            thread.interrupt();
            cancel = true;

            UPDATING = false;

            if (!downloadComplete) {
                JOptionPane.showMessageDialog(SparkManager.getMainWindow(),
                        Res.getString("message.updating.cancelled"), Res.getString("title.cancelled"),
                        JOptionPane.ERROR_MESSAGE);
            }

        }
    });
    frame.setVisible(true);
    thread.start();

    timer.scheduleAtFixedRate(new TimerTask() {
        int seconds = 1;

        public void run() {
            ByteFormat formatter = new ByteFormat();
            long value = bar.getValue();
            long average = value / seconds;
            String text = formatter.format(average) + "/Sec";

            String total = formatter.format(value);
            titlePanel.setDescription(Res.getString("message.version", version.getVersion()) + " \n"
                    + Res.getString("message.file.size", sizeText) + "\n"
                    + Res.getString("message.transfer.rate") + ": " + text + "\n"
                    + Res.getString("message.total.downloaded") + ": " + total);
            seconds++;
        }
    }, 1000, 1000);
}

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);
            }//from   w w w.ja  va  2s  .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.j  a  v  a 2s.c  o m*/
            } 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);/*from w  w w.  java 2  s . c o 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  . jav  a 2s .c  o m*/

    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.openmicroscopy.shoola.env.data.util.StatusLabel.java

/** Initializes the components.*/
private void initialize() {
    step = 0;/*from   w  w  w .  java  2s.c  o  m*/
    sizeUpload = 0;
    fileSize = "";
    seriesCount = 0;
    readerType = "";
    markedAsCancel = false;
    cancellable = true;
    totalUploadedSize = 0;
    generalLabel = new JLabel(DEFAULT_TEXT);
    Font f = generalLabel.getFont();
    Font derived = f.deriveFont(f.getStyle(), f.getSize() - 2);
    uploadBar = new JProgressBar(0, MAX);
    uploadBar.setFont(derived);
    uploadBar.setStringPainted(true);
    Dimension d = uploadBar.getPreferredSize();
    uploadBar.setPreferredSize(new Dimension(WIDTH, d.height));
    processingBar = new JProgressBar(0, STEPS.size());
    processingBar.setStringPainted(true);
    processingBar.setString(DEFAULT_TEXT);
    processingBar.setFont(derived);
    uploadBar.setVisible(false);
    processingBar.setVisible(false);
}