OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 80 | Rev 91 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
15 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.ftp.updater;
15
 
16
import org.openconcerto.ftp.FTPUtils;
17
import org.openconcerto.ftp.IFtp;
18
import org.openconcerto.utils.FileUtils;
19
 
67 ilm 20
import java.awt.AWTException;
21
import java.awt.SystemTray;
22
import java.awt.TrayIcon;
15 ilm 23
import java.io.BufferedReader;
24
import java.io.File;
25
import java.io.FileInputStream;
26
import java.io.FileReader;
27
import java.io.IOException;
65 ilm 28
import java.io.InputStream;
15 ilm 29
import java.io.InputStreamReader;
30
import java.util.Properties;
31
 
67 ilm 32
import javax.swing.ImageIcon;
15 ilm 33
import javax.swing.JOptionPane;
34
 
35
public class UpdateManager implements Runnable {
36
    private Thread thread;
37
    private String login;
38
    private String pass;
39
    private String server;
40
    private String file;
41
    private static boolean stop = false;
42
 
43
    private static final int UPDATE_COUNT = 2;
44
    private static int counter = UPDATE_COUNT;
45
    private boolean enabled;
46
 
47
    UpdateManager() {
48
 
49
        final Properties props = new Properties();
50
        final File f = new File("Configuration/update.properties");
51
        if (f.exists()) {
52
            try {
53
                props.load(new FileInputStream("Configuration/update.properties"));
54
                this.login = props.getProperty("login");
55
                this.pass = props.getProperty("pass");
56
                this.server = props.getProperty("ftpserver");
57
                this.file = props.getProperty("file");
58
                this.enabled = Boolean.parseBoolean(props.getProperty("enabled"));
59
                if (!this.enabled) {
60
                    System.out.println("Mise à jour désactivées");
61
                } else {
62
                    this.thread = new Thread(this);
63
                    this.thread.setDaemon(true);
64
                    this.thread.setPriority(Thread.MIN_PRIORITY);
65
                }
66
            } catch (IOException e) {
67
                e.printStackTrace();
68
            }
69
        } else {
70
            System.out.println("Mise à jour désactivées (fichier de configuration manquant)");
71
        }
72
 
73
    }
74
 
75
    public static synchronized void start() {
76
 
77
        UpdateManager u = new UpdateManager();
78
        if (!u.isStarted()) {
79
            u.startWatcher();
80
        } else {
81
            throw new RuntimeException("UpdateManager already started");
82
        }
83
    }
84
 
85
    public static synchronized void stop() {
86
        stop = true;
87
    }
88
 
89
    public static synchronized void forceUpdate() {
90
        counter = UPDATE_COUNT;
91
 
92
    }
93
 
94
    private boolean isStarted() {
95
        if (thread == null) {
96
            return false;
97
        }
98
        return this.thread.isAlive();
99
    }
100
 
101
    private void startWatcher() {
102
        if (this.enabled) {
103
            this.thread.start();
104
        }
105
    }
106
 
107
    @Override
108
    public void run() {
109
        System.err.println("UpdateManager started");
110
 
111
        while (!stop) {
112
            if (counter >= UPDATE_COUNT) {
113
                counter = 0;
114
                // Update
115
                final IFtp ftp = new IFtp();
116
                BufferedReader bReaderRemote = null;
117
                try {
118
                    ftp.connect(this.server);
119
 
120
                    boolean logged = ftp.login(this.login, this.pass);
121
 
122
                    if (!logged) {
123
                        throw new IllegalStateException("Identifiants refusés");
124
                    }
65 ilm 125
                    if (this.file == null) {
126
                        throw new IllegalStateException("Fichier de version non spécifié");
127
                    } else {
128
                        System.err.println("UpdateManager downloading '" + this.file + "'");
129
                    }
130
                    final InputStream retrieveFileStream = ftp.retrieveFileStream(this.file);
131
                    bReaderRemote = new BufferedReader(new InputStreamReader(retrieveFileStream));
15 ilm 132
 
133
                    int newVersion = Integer.parseInt(bReaderRemote.readLine());
134
 
135
                    BufferedReader bReaderLocal = null;
136
                    int currentVersion = -1;
137
                    try {
138
                        bReaderLocal = new BufferedReader(new FileReader(".version"));
139
                        currentVersion = Integer.parseInt(bReaderLocal.readLine());
140
                    } catch (Exception e) {
141
                        // TODO Auto-generated catch block
142
                        System.err.println(".version manquant");
143
 
144
                    } finally {
145
                        if (bReaderLocal != null) {
146
                            bReaderLocal.close();
147
                        }
148
                    }
149
 
150
                    // / marche pas: ftp.quit();
65 ilm 151
                    System.err.println("UpdateManager current version: " + currentVersion + " new version: " + newVersion);
15 ilm 152
                    if (newVersion > currentVersion) {
153
                        Object[] options = { "Maintenant", "Plus tard" };
154
                        int res = JOptionPane.showOptionDialog(null, "Une mise à jour est disponible. Installer la mise à jour:", "Mises à jour automatiques", JOptionPane.DEFAULT_OPTION,
155
                                JOptionPane.WARNING_MESSAGE, null, options, options[0]);
156
                        if (res == 0) {
157
                            update(newVersion);
158
                        }
159
 
160
                    }
161
 
162
                } catch (Exception e) {
163
                    Object[] options = { "Réessayer dans 1 minute", "Abandonner" };
164
                    int res = JOptionPane.showOptionDialog(null, "Impossible de se connecter au serveur de mises à jour.\n" + e.getMessage(), "Mises à jour automatiques", JOptionPane.DEFAULT_OPTION,
165
                            JOptionPane.WARNING_MESSAGE, null, options, options[0]);
166
                    if (res == 0) {
167
                        counter--;
168
                    } else {
169
                        stop = true;
170
                    }
171
                    e.printStackTrace();
172
 
173
                } finally {
174
                    try {
175
                        System.err.println("Disconnect start");
176
                        if (bReaderRemote != null) {
177
                            bReaderRemote.close();
178
                        }
179
                        // ftp.abort();
180
                        // ftp.logout();
181
                        // ftp.disconnect();
182
                        ftp.quit();
183
                        System.err.println("Disconnected start");
184
                    } catch (Exception e) {
185
                        e.printStackTrace();
186
                    }
187
                }
188
 
189
            }
190
            if (!stop) {
191
                try {
192
                    // Sleep 1 minute
193
                    Thread.sleep(60 * 1000);
194
                } catch (InterruptedException e) {
195
                    e.printStackTrace();
196
                }
197
            }
198
            counter++;
199
        }
200
        System.err.println("UpdateManager stopped");
201
    }
202
 
203
    private void update(int toVersion) {
67 ilm 204
 
205
        try {
80 ilm 206
            SystemTray.getSystemTray().add(new TrayIcon(new ImageIcon(UpdateManager.class.getResource("tray.png")).getImage()));
67 ilm 207
        } catch (AWTException e2) {
208
            e2.printStackTrace();
209
        }
210
        displayMessage("Préparation de la mise à jour");
15 ilm 211
        System.out.println("Update application");
212
        File tempDir = new File("Update");
213
        if (tempDir.exists()) {
214
            FileUtils.rmR(tempDir);
215
 
216
        }
217
        tempDir.mkdir();
65 ilm 218
        if (!tempDir.exists()) {
219
            JOptionPane.showMessageDialog(null, "Impossible de créer le dossier Update\nVérifiez les permissions des fichiers ou lancez le logiciel en tant qu'administrateur");
220
            return;
221
        }
15 ilm 222
        File f = new File("Update/.version");
223
        try {
67 ilm 224
            FileUtils.write(String.valueOf(toVersion) + "\n", f);
225
        } catch (IOException e1) {
65 ilm 226
            JOptionPane.showMessageDialog(null, "Impossible de créer le .version\nVérifiez les permissions des fichiers ou lancez le logiciel en tant qu'administrateur");
227
            return;
15 ilm 228
        }
229
        final IFtp ftp = new IFtp();
230
        try {
67 ilm 231
            displayMessage("Connexion au serveur");
15 ilm 232
            ftp.connect(this.server);
233
            boolean logged = ftp.login(this.login, this.pass);
234
            if (!logged) {
235
                JOptionPane.showMessageDialog(null, "Impossible d'accéder au serveur FTP pour récupérer les fichiers");
236
                ftp.disconnect();
237
                return;
238
            }
239
            String dir = this.file;
240
            int i = dir.lastIndexOf('.');
241
            if (i > 0) {
242
                dir = dir.substring(0, i);
243
            }
244
 
245
            boolean cwdOk = ftp.changeWorkingDirectory(dir);
246
            if (!cwdOk) {
247
                JOptionPane.showMessageDialog(null, "Impossible d'accéder au dossier " + dir + " du serveur FTP");
248
                ftp.disconnect();
249
                return;
250
            }
67 ilm 251
            displayMessage("Téléchargement des fichiers");
15 ilm 252
            FTPUtils.saveR(ftp, tempDir);
253
 
254
            if (tempDir.getAbsolutePath().contains("workspace") && !tempDir.getAbsolutePath().contains("dist")) {
255
                JOptionPane.showMessageDialog(null, "Mise à jour desactivée en version non 'dist'");
256
                ftp.disconnect();
257
                return;
258
            }
65 ilm 259
 
28 ilm 260
            final String updaterFilename = "Update" + File.separator + "update.jar";
15 ilm 261
            if (!new File(updaterFilename).exists()) {
28 ilm 262
                JOptionPane.showMessageDialog(null, "Le fichier 'Update/update.jar' est manquant.");
15 ilm 263
                ftp.disconnect();
264
                return;
265
            }
67 ilm 266
            displayMessage("Copie des fichiers");
267
            try {
268
                ftp.disconnect();
269
            } catch (Throwable e) {
270
                e.printStackTrace();
271
            }
83 ilm 272
            String jHome = System.getProperty("java.home");
273
            jHome += File.separatorChar + "bin" + File.separatorChar + "java";
274
            Runtime.getRuntime().exec("\"" + jHome + "\" -jar " + updaterFilename);
275
            JOptionPane.showMessageDialog(null, "Mise à jour terminée");
15 ilm 276
            System.exit(0);
277
 
278
        } catch (Exception e) {
279
            e.printStackTrace();
280
            JOptionPane.showMessageDialog(null, "Impossible de récupérer les fichiers");
281
 
282
        }
283
 
284
    }
67 ilm 285
 
286
    void displayMessage(String s) {
287
        try {
288
            SystemTray.getSystemTray().getTrayIcons()[0].displayMessage("Mise à jour en cours", s, TrayIcon.MessageType.INFO);
289
        } catch (Throwable e) {
290
            e.printStackTrace();
291
        }
292
    }
15 ilm 293
}