OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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

Rev Author Line No. Line
17 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.utils;
15
 
16
import java.io.File;
17
import java.io.FileInputStream;
18
import java.io.FileNotFoundException;
19
import java.io.FileOutputStream;
20
import java.io.IOException;
21
import java.io.InputStream;
22
import java.math.BigInteger;
23
import java.security.MessageDigest;
24
import java.security.NoSuchAlgorithmException;
83 ilm 25
import java.util.HashSet;
26
import java.util.Set;
17 ilm 27
import java.util.logging.Level;
28
import java.util.logging.Logger;
29
 
30
import javax.swing.JOptionPane;
31
import javax.swing.SwingUtilities;
32
 
33
public class Backup {
34
 
35
    static public final Logger getLogger() {
36
        return Logger.getLogger("org.openconcerto.backup");
37
    }
38
 
83 ilm 39
    private Set<String> processedDir;
17 ilm 40
    private final File dest;
41
 
42
    public Backup(File dest) {
43
        this.dest = dest;
44
    }
45
 
46
    static final int bufferSize = 512 * 1024;
47
 
48
    /**
49
     * Copy of File
50
     *
51
     * @param sourceFile
52
     * @param destFile
53
     * @param bar
54
     */
55
    private int copy(final File sourceFile, File destFile) {
56
        int failed = 0;
57
 
58
        if (sourceFile.isDirectory()) {
59
            destFile.mkdirs();
60
            return 0;
61
        }
62
 
63
        try {
64
            if (destFile.exists()) {
65
                destFile.delete();
66
            }
67
            destFile.createNewFile();
68
        } catch (IOException e1) {
69
            e1.printStackTrace();
70
        }
71
 
72
        try {
73
            FileOutputStream bufOut = new FileOutputStream(destFile);
74
            FileInputStream bufIn = new FileInputStream(sourceFile);
75
 
76
            try {
77
 
78
                byte buffer[] = new byte[bufferSize];
79
                int nbLecture;
80
                while ((nbLecture = bufIn.read(buffer)) != -1) {
81
                    bufOut.write(buffer, 0, nbLecture);
82
                }
83
 
84
            } catch (IOException e) {
85
                getLogger().log(Level.SEVERE, "Copy Failed for file : " + sourceFile);
86
                System.err.println("Failed : " + sourceFile);
87
                failed = 1;
88
                e.printStackTrace();
89
            } finally {
90
                try {
91
 
92
                    bufIn.close();
93
                    bufOut.close();
94
                } catch (IOException e) {
95
                    getLogger().log(Level.SEVERE, "Error to close Stream in copy." + sourceFile);
96
                    failed = 1;
97
                    e.printStackTrace();
98
                }
99
            }
100
 
101
        } catch (FileNotFoundException e) {
102
            getLogger().log(Level.SEVERE, "Copy Failed, File not found " + sourceFile);
103
            failed = 1;
104
            e.printStackTrace();
105
        }
106
 
107
        destFile.setLastModified(sourceFile.lastModified());
108
        return failed;
109
    }
110
 
111
    /**
112
     * Recherche les fichiers à créer dans le répertoire passé en parametre
113
     *
114
     * @param dir
115
     * @return le nombre d'erreurs
116
     */
117
    public int applyTo(final File dir) {
118
        getLogger().log(Level.INFO, "Copy start from " + dir + " to " + this.dest);
83 ilm 119
        processedDir = new HashSet<String>();
120
        final int applyTo = applyTo(dir, dir);
121
        processedDir = null;
122
        return applyTo;
17 ilm 123
    }
124
 
125
    private int applyTo(final File origine, final File dir) {
83 ilm 126
        final String dirPath = dir.getAbsolutePath();
127
        if (processedDir.contains(dirPath)) {
128
            return 0;
129
        }
130
        processedDir.add(dirPath);
17 ilm 131
        int failed = 0;
132
        if (dir.exists()) {
133
 
134
            File file = getFile(origine, dir);
135
            if (!file.exists()) {
136
                file.mkdirs();
137
            }
138
            File[] list = dir.listFiles();
139
            if (list != null) {
140
                for (int i = 0; i < list.length; i++) {
141
                    File f = list[i];
142
                    File f2 = getFile(origine, f);
143
 
144
                    // si c'est un répertoire
145
                    if (f.isDirectory()) {
146
                        if (!f2.exists()) {
147
                            failed += copy(f, f2);
148
                        }
149
                        applyTo(origine, f);
150
                    } else {
151
                        if (f2.exists()) {
152
                            // On copie si la date de modification ou la taille sont differente
153
                            boolean dateModif = f.lastModified() == f2.lastModified();
154
                            if (!dateModif || f.length() != f2.length()) {
155
                                failed += copy(f, f2);
156
                            } else {
157
                                // Sinon si la taille est égale on vérifie si le fichier est le meme
158
                                if (!dateModif && f.length() == f2.length()) {
159
                                    String MD5f = getMD5(f);
160
                                    String MD5f2 = getMD5(f2);
161
                                    boolean md5 = MD5f.equalsIgnoreCase(MD5f2);
162
                                    if (!(MD5f.length() > 0 && MD5f2.length() > 0)) {
163
                                        if (md5) {
164
                                            f2.setLastModified(f.lastModified());
165
                                        } else {
166
                                            failed += copy(f, f2);
167
                                        }
168
                                    } else {
169
                                        failed += copy(f, f2);
170
                                    }
171
                                }
172
                            }
173
                        } else {
174
                            failed += copy(f, f2);
175
                        }
176
                    }
177
                }
178
            } else {
179
                failed++;
180
                SwingUtilities.invokeLater(new Runnable() {
181
                    @Override
182
                    public void run() {
183
                        JOptionPane.showMessageDialog(null, "Impossible de lister le répertoire " + dir + ".\n Vous n'avez pas les droits suffisants!");
184
                    }
185
                });
186
 
187
            }
188
 
189
        }
190
        return failed;
191
    }
192
 
193
    /**
194
     * Get the new path for the saved file
195
     *
196
     * @param f File to save
197
     * @return
198
     */
199
    private File getFile(File origine, File f) {
200
 
201
        File base = (origine.getParentFile() == null) ? origine : origine.getParentFile();
202
        String s2 = base.toURI().relativize(f.toURI()).getPath();
203
 
204
        return new File(this.dest, s2);
205
    }
206
 
207
    /**
208
     *
209
     * @param f File
210
     * @return the md5 of the File
211
     */
212
    private String getMD5(File f) {
213
        MessageDigest digest;
214
        String output = "";
215
        InputStream is;
216
        try {
217
            is = new FileInputStream(f);
218
 
219
            try {
220
                digest = MessageDigest.getInstance("MD5");
221
 
222
                is = new FileInputStream(f);
223
                byte buffer[] = new byte[512 * 1024];
224
                int read = 0;
225
 
226
                while ((read = is.read(buffer)) > 0) {
227
                    digest.update(buffer, 0, read);
228
                }
229
                byte[] md5sum = digest.digest();
230
                BigInteger bigInt = new BigInteger(1, md5sum);
231
                output = bigInt.toString(16);
232
                // System.out.println("MD5: " + output);
233
 
234
                is.close();
235
            } catch (IOException e) {
236
                getLogger().log(Level.INFO, "Unable to process file for MD5. " + f);
237
                throw new RuntimeException("Unable to process file for MD5", e);
238
            } catch (NoSuchAlgorithmException e) {
239
                // TODO Auto-generated catch block
240
                e.printStackTrace();
241
            } finally {
242
                try {
243
                    is.close();
244
                } catch (IOException e) {
245
                    getLogger().log(Level.INFO, "Unable to close file at the end of MD5. " + f);
246
                    e.printStackTrace();
247
                }
248
            }
249
        } catch (FileNotFoundException e1) {
250
            getLogger().log(Level.INFO, "File not found for MD5. " + f);
251
            e1.printStackTrace();
252
        }
253
 
254
        return output;
255
 
256
    }
257
 
258
    public void close() {
259
    }
260
}