checkupdates.java

来自「开源项目openfire的完整源程序」· Java 代码 · 共 668 行 · 第 1/2 页

JAVA
668
字号
                if (bytesRead < 0) {
                    break;
                }
                out.write(buffer, 0, bytesRead);
                read += bytesRead;
                bar.setValue(read);
            }
        }
        catch (IOException e) {
            Log.error(e);
        }
    }

    /**
     * Checks Spark Manager and/or Jive Software for the latest version of Spark.
     *
     * @param explicit true if the user explicitly asks for the latest version.
     * @throws Exception
     */
    public void checkForUpdate(boolean explicit) throws Exception {
        if (UPDATING) {
            return;
        }

        UPDATING = true;

        if (isLocalBuildAvailable()) {
            return;
        }

        LocalPreferences localPreferences = SettingsManager.getLocalPreferences();

        Date lastChecked = localPreferences.getLastCheckForUpdates();
        if (lastChecked == null) {
            lastChecked = new Date();
            // This is the first invocation of Communicator
            localPreferences.setLastCheckForUpdates(lastChecked);
            SettingsManager.saveSettings();
        }

        // Check to see if it has been a week
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(lastChecked);
        calendar.add(Calendar.DATE, 7);

        final Date lastCheckedPlusAWeek = calendar.getTime();

        boolean weekOrLonger = new Date().getTime() >= lastCheckedPlusAWeek.getTime();


        if (weekOrLonger || explicit || sparkPluginInstalled) {
            // Check version on server.
            lastChecked = new Date();
            localPreferences.setLastCheckForUpdates(lastChecked);
            SettingsManager.saveSettings();

            final SparkVersion serverVersion = newBuildAvailable();
            if (serverVersion == null) {
                UPDATING = false;

                if (explicit) {
                    JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "There are no updates.", "No Updates", JOptionPane.INFORMATION_MESSAGE);
                }
                return;
            }

            // Otherwise updates are available
            String downloadURL = serverVersion.getDownloadURL();
            String filename = downloadURL.substring(downloadURL.lastIndexOf("/") + 1);

            if (filename.indexOf('=') != -1) {
                filename = filename.substring(filename.indexOf('=') + 1);
            }

            // Set Download Directory 
            final File downloadDir = new File(Spark.getSparkUserHome(), "updates");
            downloadDir.mkdirs();

            // Set file to download.
            final File fileToDownload = new File(downloadDir, filename);
            if (fileToDownload.exists()) {
                fileToDownload.delete();
            }

            ConfirmDialog confirm = new ConfirmDialog();
            confirm.showConfirmDialog(SparkManager.getMainWindow(), Res.getString("title.new.version.available"),
                    Res.getString("message.new.spark.available", filename), Res.getString("yes"), Res.getString("no"),
                    null);
            confirm.setDialogSize(400, 300);
            confirm.setConfirmListener(new ConfirmListener() {
                public void yesOption() {
                    SwingWorker worker = new SwingWorker() {
                        public Object construct() {
                            try {
                                Thread.sleep(50);
                            }
                            catch (InterruptedException e) {
                                Log.error(e);
                            }
                            return "ok";
                        }

                        public void finished() {
                            if (Spark.isWindows()) {
                                downloadUpdate(fileToDownload, serverVersion);
                            }
                            else {
                                // Launch browser to download page.
                                try {
                                    if (sparkPluginInstalled) {
                                        BrowserLauncher.openURL(serverVersion.getDownloadURL());
                                    }
                                    else {
                                        BrowserLauncher.openURL("http://www.igniterealtime.org/downloads/index.jsp#spark");
                                    }
                                }

                                catch (IOException e) {
                                    Log.error(e);
                                }
                                UPDATING = false;
                            }
                        }

                    };
                    worker.start();
                }

                public void noOption() {
                    UPDATING = false;
                }
            });
        }
        else {
            UPDATING = false;
        }

    }


    /**
     * Returns true if the first version number is greater than the second.
     *
     * @param firstVersion  the first version number.
     * @param secondVersion the second version number.
     * @return returns true if the first version is greater than the second.
     */
    public static boolean isGreater(String firstVersion, String secondVersion) {
        int indexOne = firstVersion.indexOf("_");
        if (indexOne != -1) {
            firstVersion = firstVersion.substring(indexOne + 1);
        }

        int indexTwo = secondVersion.indexOf("_");
        if (indexTwo != -1) {
            secondVersion = secondVersion.substring(indexTwo + 1);
        }

        firstVersion = firstVersion.replaceAll(".online", "");
        secondVersion = secondVersion.replace(".online", "");

        boolean versionOneBetaOrAlpha = firstVersion.toLowerCase().contains("beta") || firstVersion.toLowerCase().contains("alpha");
        boolean versionTwoBetaOrAlpha = secondVersion.toLowerCase().contains("beta") || secondVersion.toLowerCase().contains("alpha");

        // Handle case where they are both betas / alphas
        if ((versionOneBetaOrAlpha && versionTwoBetaOrAlpha) || (!versionOneBetaOrAlpha && !versionTwoBetaOrAlpha)) {
            return firstVersion.compareTo(secondVersion) >= 1;
        }

        // Handle the case where version 1 is a beta or alpha
        if (versionOneBetaOrAlpha) {
            String versionOne = getVersion(firstVersion);
            return versionOne.compareTo(secondVersion) >= 1;
        }
        else if (versionTwoBetaOrAlpha) {
            String versionTwo = getVersion(secondVersion);
            int result = firstVersion.compareTo(versionTwo);
            return result >= 0;
        }


        return firstVersion.compareTo(secondVersion) >= 1;
    }

    public static String getVersion(String version) {
        int lastIndexOf = version.lastIndexOf(".");
        if (lastIndexOf != -1) {
            return version.substring(0, lastIndexOf);
        }

        return version;

    }

    /**
     * Returns the latest version of Spark available via Spark Manager or Jive Software.
     *
     * @param connection the XMPPConnection to use.
     * @return the information for about the latest Spark Client.
     * @throws XMPPException
     */
    public static SparkVersion getLatestVersion(XMPPConnection connection) throws XMPPException {
        SparkVersion request = new SparkVersion();
        request.setType(IQ.Type.GET);
        request.setTo("updater." + connection.getServiceName());

        PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(request.getPacketID()));
        connection.sendPacket(request);


        SparkVersion response = (SparkVersion)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());

        // Cancel the collector.
        collector.cancel();
        if (response == null) {
            throw new XMPPException("No response from server.");
        }
        if (response.getError() != null) {
            throw new XMPPException(response.getError());
        }
        return response;
    }

    /**
     * Does a service discvery on the server to see if a Spark Manager
     * is enabled.
     *
     * @param con the XMPPConnection to use.
     * @return true if Spark Manager is available.
     */
    public static boolean isSparkPluginInstalled(XMPPConnection con) {
        if (!con.isConnected()) {
            return false;
        }


        try {
            DiscoverItems items = SparkManager.getSessionManager().getDiscoveredItems();
            Iterator iter = items.getItems();
            while (iter.hasNext()) {
                DiscoverItems.Item item = (DiscoverItems.Item)iter.next();
                if ("Spark Updater".equals(item.getName())) {
                    return true;
                }
            }
        }
        catch (Exception e) {
            Log.error(e);
        }

        return false;

    }

    /**
     * Prompts the user to install the latest Spark.
     *
     * @param downloadedFile the location of the latest downloaded client.
     * @param title          the title
     * @param message        the message
     */
    private void promptForInstallation(final File downloadedFile, String title, String message) {
        ConfirmDialog confirm = new ConfirmDialog();
        confirm.showConfirmDialog(SparkManager.getMainWindow(), title,
                message, Res.getString("yes"), Res.getString("no"),
                null);
        confirm.setConfirmListener(new ConfirmListener() {
            public void yesOption() {
                try {
                    if (Spark.isWindows()) {
                        Runtime.getRuntime().exec(downloadedFile.getAbsolutePath());
                    }
                    else if (Spark.isMac()) {
                        Runtime.getRuntime().exec("open " + downloadedFile.getCanonicalPath());
                    }
                }
                catch (IOException e) {
                    Log.error(e);
                }
                SparkManager.getMainWindow().shutdown();
            }

            public void noOption() {

            }
        });
    }

    /**
     * Checks to see if a new version of Spark has already been downloaded by not installed.
     *
     * @return true if a newer version exists.
     */
    private boolean isLocalBuildAvailable() {
        // Check the bin directory for previous downloads. If there is a
        // newer version of Spark, ask if they wish to install.
        if (Spark.isWindows()) {
            File binDirectory = Spark.getBinDirectory();
            File[] files = binDirectory.listFiles();
            int no = files != null ? files.length : 0;
            for (int i = 0; i < no; i++) {
                File file = files[i];
                String fileName = file.getName();
                if (fileName.endsWith(".exe")) {
                    int index = fileName.indexOf("_");

                    // Add version number
                    String versionNumber = fileName.substring(index + 1);
                    int indexOfPeriod = versionNumber.indexOf(".");

                    versionNumber = versionNumber.substring(0, indexOfPeriod);
                    versionNumber = versionNumber.replaceAll("_online", "");
                    versionNumber = versionNumber.replaceAll("_", ".");

                    boolean isGreater = versionNumber.compareTo(JiveInfo.getVersion()) >= 1;
                    if (isGreater) {
                        // Prompt
                        promptForInstallation(file, Res.getString("title.new.client.available"), Res.getString("message.restart.spark.to.install"));
                        return true;
                    }
                    else {
                        file.delete();
                    }

                }
            }
        }

        return false;
    }


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?