com.peter.javaautoupdater.JavaAutoUpdater.java Source code

Java tutorial

Introduction

Here is the source code for com.peter.javaautoupdater.JavaAutoUpdater.java

Source

/*
 * Copyright (C) 2016 peter.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */
package com.peter.javaautoupdater;

import com.peterswing.advancedswing.jprogressbardialog.JProgressBarDialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamAdapter;

/**
 *
 * @author peter, mcheung63@hotmail.com
 */
public class JavaAutoUpdater {

    static boolean isDebug;
    static String basePath;
    static String softwareName;
    static String args[];
    static String jarPathWithJarName = new File(
            JavaAutoUpdater.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getAbsolutePath();
    static String jarName = new java.io.File(
            JavaAutoUpdater.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();

    public static void main(String args[]) {

    }

    public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword, String basePath,
            String softwareName, String args[]) {
        run(ftpHost, ftpPort, ftpUsername, ftpPassword, false, false, basePath, softwareName, args);
    }

    public static void run(String ftpHost, int ftpPort, String ftpUsername, String ftpPassword,
            boolean isLocalPassiveMode, boolean isRemotePassiveMode, String basePath, String softwareName,
            String args[]) {
        System.out.println("jarName=" + jarName);
        for (String arg : args) {
            if (arg.toLowerCase().trim().equals("-noautoupdate")) {
                return;
            }
        }
        JavaAutoUpdater.basePath = basePath;
        JavaAutoUpdater.softwareName = softwareName;
        JavaAutoUpdater.args = args;

        if (!jarName.endsWith(".jar") || jarName.startsWith("JavaAutoUpdater-")) {
            if (isDebug) {
                jarName = "test.jar";
            } else {
                return;
            }
        }
        JProgressBarDialog d = new JProgressBarDialog(new JFrame(), "Auto updater", true);

        d.progressBar.setIndeterminate(true);
        d.progressBar.setStringPainted(true);
        d.progressBar.setString("Updating");
        //      d.addCancelEventListener(this);
        Thread longRunningThread = new Thread() {
            public void run() {
                d.progressBar.setString("checking latest version");
                System.out.println("checking latest version");

                FTPClient ftp = new FTPClient();
                try {
                    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
                    ftp.connect(ftpHost, ftpPort);
                    int reply = ftp.getReplyCode();
                    System.out.println("reply=" + reply + ", " + FTPReply.isPositiveCompletion(reply));
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftp.disconnect();
                        JOptionPane.showMessageDialog(null, "FTP server refused connection", "error",
                                JOptionPane.ERROR_MESSAGE);
                    }
                    d.progressBar.setString("connected to ftp");
                    System.out.println("connected to ftp");
                    boolean success = ftp.login(ftpUsername, ftpPassword);
                    if (!success) {
                        ftp.disconnect();
                        JOptionPane.showMessageDialog(null, "FTP login fail, can't update software", "error",
                                JOptionPane.ERROR_MESSAGE);
                    }
                    if (isLocalPassiveMode) {
                        ftp.enterLocalPassiveMode();
                    }
                    if (isRemotePassiveMode) {
                        ftp.enterRemotePassiveMode();
                    }
                    FTPFile[] ftpFiles = ftp.listFiles(basePath, new FTPFileFilter() {
                        @Override
                        public boolean accept(FTPFile file) {
                            if (file.getName().startsWith(softwareName)) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    });
                    if (ftpFiles.length > 0) {
                        FTPFile targetFile = ftpFiles[ftpFiles.length - 1];
                        System.out.println("targetFile : " + targetFile.getName() + " , " + targetFile.getSize()
                                + "!=" + new File(jarName).length());
                        if (!targetFile.getName().equals(jarName)
                                || targetFile.getSize() != new File(jarName).length()) {
                            int r = JOptionPane.showConfirmDialog(null,
                                    "Confirm to update to " + targetFile.getName(), "Question",
                                    JOptionPane.YES_NO_OPTION);
                            if (r == JOptionPane.YES_OPTION) {
                                //ftp.enterRemotePassiveMode();
                                d.progressBar.setString("downloading " + targetFile.getName());
                                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                                ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);

                                d.progressBar.setIndeterminate(false);
                                d.progressBar.setMaximum(100);
                                CopyStreamAdapter streamListener = new CopyStreamAdapter() {

                                    @Override
                                    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                                            long streamSize) {
                                        int percent = (int) (totalBytesTransferred * 100 / targetFile.getSize());
                                        d.progressBar.setValue(percent);
                                    }
                                };
                                ftp.setCopyStreamListener(streamListener);
                                try (FileOutputStream fos = new FileOutputStream(targetFile.getName())) {
                                    ftp.retrieveFile(basePath + "/" + targetFile.getName(), fos);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                d.progressBar.setString("restarting " + targetFile.getName());
                                restartApplication(targetFile.getName());
                            }
                        }

                    }
                    ftp.logout();
                    ftp.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
        d.thread = longRunningThread;
        d.setVisible(true);
    }

    static void restartApplication(String jarName) {
        try {
            final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator
                    + "java";
            System.out.println("javaBin=" + javaBin);
            //final File currentJar = new File(JavaAutoUpdater.class.getProtectionDomain().getCodeSource().getLocation().toURI());

            /* is it a jar file? */
            if (!jarName.endsWith(".jar")) {
                return;
            }

            /* Build command: java -jar application.jar */
            final ArrayList<String> command = new ArrayList<String>();
            command.add(javaBin);
            command.add("-jar");
            //System.out.println("path=" + new File(JavaAutoUpdater.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent());
            command.add(jarName);
            if (args != null) {
                for (String arg : args) {
                    command.add(arg);
                }
            }
            command.add("-noautoupdate");

            //System.out.println("command=" + command);
            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}