OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | 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
 *
182 ilm 4
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
17 ilm 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
 
83 ilm 16
import org.openconcerto.utils.CollectionMap2.Mode;
180 ilm 17
import org.openconcerto.utils.DesktopEnvironment.Gnome;
80 ilm 18
import org.openconcerto.utils.OSFamily.Unix;
17 ilm 19
import org.openconcerto.utils.StringUtils.Escaper;
20
import org.openconcerto.utils.cc.ExnTransformer;
21
import org.openconcerto.utils.cc.IClosure;
22
 
23
import java.awt.Desktop;
24
import java.io.BufferedReader;
25
import java.io.BufferedWriter;
26
import java.io.File;
27
import java.io.FileFilter;
28
import java.io.FileInputStream;
67 ilm 29
import java.io.FileNotFoundException;
17 ilm 30
import java.io.FileOutputStream;
31
import java.io.IOException;
32
import java.io.InputStream;
33
import java.io.InputStreamReader;
34
import java.io.OutputStreamWriter;
35
import java.io.RandomAccessFile;
36
import java.io.Reader;
90 ilm 37
import java.net.URI;
17 ilm 38
import java.net.URL;
39
import java.nio.channels.FileChannel;
67 ilm 40
import java.nio.charset.Charset;
156 ilm 41
import java.nio.charset.StandardCharsets;
144 ilm 42
import java.nio.file.CopyOption;
43
import java.nio.file.DirectoryStream;
44
import java.nio.file.DirectoryStream.Filter;
45
import java.nio.file.FileVisitResult;
46
import java.nio.file.Files;
47
import java.nio.file.LinkOption;
180 ilm 48
import java.nio.file.OpenOption;
144 ilm 49
import java.nio.file.Path;
50
import java.nio.file.SimpleFileVisitor;
51
import java.nio.file.StandardCopyOption;
180 ilm 52
import java.nio.file.StandardOpenOption;
144 ilm 53
import java.nio.file.attribute.BasicFileAttributes;
54
import java.nio.file.attribute.PosixFileAttributeView;
55
import java.nio.file.attribute.PosixFilePermissions;
17 ilm 56
import java.util.ArrayList;
57
import java.util.Arrays;
58
import java.util.Collection;
59
import java.util.Collections;
144 ilm 60
import java.util.EnumSet;
17 ilm 61
import java.util.HashMap;
144 ilm 62
import java.util.HashSet;
17 ilm 63
import java.util.List;
64
import java.util.Map;
83 ilm 65
import java.util.Map.Entry;
180 ilm 66
import java.util.Objects;
17 ilm 67
import java.util.Set;
67 ilm 68
import java.util.logging.Level;
73 ilm 69
import java.util.regex.Pattern;
17 ilm 70
 
71
public final class FileUtils {
72
 
180 ilm 73
    public static void main(String[] args) throws Exception {
74
        final String cmd = args[0];
75
        if ("browseFile".equals(cmd))
76
            browseFile(new File(args[1]));
77
        else if ("browse".equals(cmd))
78
            browse(new URI(args[1]));
79
        else
80
            System.err.println("Unkown command : " + cmd);
81
    }
82
 
17 ilm 83
    private FileUtils() {
84
        // all static
85
    }
86
 
93 ilm 87
    public static void browseFile(final File f) throws IOException {
180 ilm 88
        browse(null, Objects.requireNonNull(f));
89
    }
93 ilm 90
 
180 ilm 91
    private static void browse(URI uri, final File f) throws IOException {
92
        assert (uri == null) != (f == null);
93
        boolean handled = false;
94
        final Desktop.Action action = Desktop.Action.BROWSE;
95
        if (isDesktopDesirable(action) && Desktop.isDesktopSupported()) {
96
            final Desktop d = Desktop.getDesktop();
97
            if (d.isSupported(action)) {
98
                if (uri == null)
99
                    uri = f.getCanonicalFile().toURI();
100
                if (!uri.getScheme().equals("file") && DesktopEnvironment.getDE() instanceof Gnome) {
101
                    ProcessBuilder pb = null;
102
                    final String version = DesktopEnvironment.getDE().getVersion();
103
                    // Ubuntu 12.04, 14.04, 16.04
104
                    if (version.startsWith("3.4.") || version.startsWith("3.10.") || version.startsWith("3.18.")) {
105
                        pb = new ProcessBuilder("gvfs-mount", uri.toASCIIString());
106
                        // Ubuntu 18.04
107
                    } else if (version.startsWith("3.28")) {
108
                        // gio/gio-tool-mount.c#mount() calls g_file_mount_enclosing_volume.
109
                        // TODO find out how glib computes "the volume that contains the file
110
                        // location". E.g why does mount "davs://example.com/webdav/dir/dir" mounts
111
                        // "davs://example.com/webdav/".
112
                        // Return 0 if not yet mounted, 2 if it was already mounted.
113
                        pb = new ProcessBuilder("gio", "mount", uri.toASCIIString());
114
                    }
115
                    if (pb != null) {
116
                        try {
117
                            startDiscardingOutput(pb).waitFor();
118
                        } catch (InterruptedException e) {
119
                            throw new RTInterruptedException("Interrupted while waiting on mount for " + uri, e);
120
                        }
121
                    }
122
                }
123
                d.browse(uri);
124
                handled = true;
17 ilm 125
            }
126
        }
180 ilm 127
        if (!handled) {
128
            // if the caller passed a file use it instead of our converted URI
129
            if (f != null)
130
                openNative(f);
131
            else
132
                openNative(uri);
133
        }
17 ilm 134
    }
135
 
180 ilm 136
    public static boolean isDesktopDesirable(Desktop.Action action) {
137
        // apparently the JRE just checks if gnome libs are available (e.g. open Nautilus in XFCE)
138
        return !(action == Desktop.Action.BROWSE && OSFamily.getInstance() == OSFamily.Linux && !(DesktopEnvironment.getDE() instanceof Gnome));
90 ilm 139
    }
140
 
180 ilm 141
    public static void browse(URI uri) throws IOException {
142
        browse(Objects.requireNonNull(uri), null);
143
    }
144
 
17 ilm 145
    public static void openFile(File f) throws IOException {
156 ilm 146
        if (!f.exists()) {
147
            throw new FileNotFoundException(f.getAbsolutePath() + " not found");
148
        }
17 ilm 149
        if (Desktop.isDesktopSupported()) {
150
            Desktop d = Desktop.getDesktop();
151
            if (d.isSupported(Desktop.Action.OPEN)) {
152
                d.open(f.getCanonicalFile());
153
            } else {
154
                openNative(f);
155
            }
156
        } else {
157
            openNative(f);
158
        }
159
    }
160
 
80 ilm 161
    // immutable, getAbsoluteFile() required otherwise list() returns null
162
    static private final File WD = new File("").getAbsoluteFile();
163
 
164
    static public final File getWD() {
165
        return WD;
166
    }
167
 
17 ilm 168
    /**
169
     * All the files (see {@link File#isFile()}) contained in the passed dir.
170
     *
171
     * @param dir the root directory to search.
172
     * @return a List of String.
173
     */
174
    public static List<String> listR(File dir) {
61 ilm 175
        return listR(dir, REGULAR_FILE_FILTER);
17 ilm 176
    }
177
 
61 ilm 178
    public static List<String> listR(File dir, FileFilter ff) {
179
        return listR_rec(dir, ff, ".");
180
    }
181
 
182
    private static List<String> listR_rec(File dir, FileFilter ff, String prefix) {
17 ilm 183
        if (!dir.isDirectory())
184
            return null;
185
 
186
        final List<String> res = new ArrayList<String>();
187
        final File[] children = dir.listFiles();
188
        for (int i = 0; i < children.length; i++) {
189
            final String newPrefix = prefix + "/" + children[i].getName();
61 ilm 190
            if (ff == null || ff.accept(children[i])) {
17 ilm 191
                res.add(newPrefix);
192
            }
61 ilm 193
            if (children[i].isDirectory()) {
194
                res.addAll(listR_rec(children[i], ff, newPrefix));
195
            }
17 ilm 196
        }
197
        return res;
198
    }
199
 
200
    public static void walk(File dir, IClosure<File> c) {
201
        walk(dir, c, RecursionType.BREADTH_FIRST);
202
    }
203
 
204
    public static void walk(File dir, IClosure<File> c, RecursionType type) {
205
        if (type == RecursionType.BREADTH_FIRST)
206
            c.executeChecked(dir);
207
        if (dir.isDirectory()) {
208
            for (final File child : dir.listFiles()) {
209
                walk(child, c, type);
210
            }
211
        }
212
        if (type == RecursionType.DEPTH_FIRST)
213
            c.executeChecked(dir);
214
    }
215
 
216
    public static final List<File> list(File root, final int depth) {
217
        return list(root, depth, null);
218
    }
219
 
220
    /**
221
     * Finds all files at the specified depth below <code>root</code>.
222
     *
223
     * @param root the base directory
224
     * @param depth the depth of the returned files.
225
     * @param ff a filter, can be <code>null</code>.
226
     * @return a list of files <code>depth</code> levels beneath <code>root</code>.
227
     */
228
    public static final List<File> list(File root, final int depth, final FileFilter ff) {
61 ilm 229
        return list(root, depth, depth, ff);
230
    }
231
 
232
    public static final List<File> list(final File root, final int minDepth, final int maxDepth, final FileFilter ff) {
233
        return list(root, minDepth, maxDepth, ff, false);
234
    }
235
 
236
    public static final List<File> list(final File root, final int minDepth, final int maxDepth, final FileFilter ff, final boolean sort) {
237
        if (minDepth > maxDepth)
238
            throw new IllegalArgumentException(minDepth + " > " + maxDepth);
239
        if (maxDepth < 0)
240
            throw new IllegalArgumentException(maxDepth + " < 0");
17 ilm 241
        if (!root.exists())
242
            return Collections.<File> emptyList();
61 ilm 243
 
244
        final File currentFile = accept(ff, minDepth, maxDepth, root, 0) ? root : null;
245
        if (maxDepth == 0) {
246
            return currentFile == null ? Collections.<File> emptyList() : Collections.singletonList(currentFile);
17 ilm 247
        } else {
61 ilm 248
            final List<File> res = new ArrayList<File>();
249
            final File[] children = root.listFiles();
250
            if (children == null)
17 ilm 251
                throw new IllegalStateException("cannot list " + root);
61 ilm 252
            if (sort)
253
                Arrays.sort(children);
254
            for (final File child : children) {
255
                if (maxDepth > 1 && child.isDirectory()) {
256
                    res.addAll(list(child, minDepth - 1, maxDepth - 1, ff, sort));
257
                } else if (accept(ff, minDepth, maxDepth, child, 1)) {
258
                    res.add(child);
259
                }
17 ilm 260
            }
61 ilm 261
            if (currentFile != null)
262
                res.add(currentFile);
17 ilm 263
            return res;
264
        }
265
    }
266
 
61 ilm 267
    private static final boolean accept(final FileFilter ff, final int minDepth, final int maxDepth, final File f, final int depth) {
268
        return minDepth <= depth && depth <= maxDepth && (ff == null || ff.accept(f));
269
    }
270
 
17 ilm 271
    /**
272
     * Returns the relative path from one file to another in the same filesystem tree. Files are not
273
     * required to exist, see {@link File#getCanonicalPath()}.
274
     *
275
     * @param fromDir the starting directory, eg /a/b/.
276
     * @param to the file to get to, eg /a/x/y.txt.
277
     * @return the relative path, eg "../x/y.txt".
278
     * @throws IOException if an error occurs while canonicalizing the files.
279
     * @throws IllegalArgumentException if fromDir exists and is not directory.
182 ilm 280
     * @see {@link Path#relativize(Path)}
17 ilm 281
     */
282
    public static final String relative(File fromDir, File to) throws IOException {
283
        if (fromDir.exists() && !fromDir.isDirectory())
284
            throw new IllegalArgumentException(fromDir + " is not a directory");
285
 
286
        final File fromF = fromDir.getCanonicalFile();
287
        final File toF = to.getCanonicalFile();
288
        final List<File> toPath = getAncestors(toF);
289
        final List<File> fromPath = getAncestors(fromF);
290
 
291
        // no common ancestor (for example on Windows on 2 different letters)
292
        if (!toPath.get(0).equals(fromPath.get(0))) {
293
            // already canonical
294
            return toF.getPath();
295
        }
296
 
297
        int commonIndex = Math.min(toPath.size(), fromPath.size()) - 1;
298
        boolean found = false;
299
        while (commonIndex >= 0 && !found) {
300
            found = fromPath.get(commonIndex).equals(toPath.get(commonIndex));
301
            if (!found)
302
                commonIndex--;
303
        }
304
 
305
        // on remonte jusqu'à l'ancêtre commun
306
        final List<String> complete = new ArrayList<String>(Collections.nCopies(fromPath.size() - 1 - commonIndex, ".."));
307
        if (complete.isEmpty())
308
            complete.add(".");
309
        // puis on descend vers 'to'
310
        for (File f : toPath.subList(commonIndex + 1, toPath.size())) {
311
            complete.add(f.getName());
312
        }
313
 
314
        return CollectionUtils.join(complete, File.separator);
315
    }
316
 
317
    // return each ancestor of f (including itself)
318
    // eg [/, /folder, /folder/dir] for /folder/dir
319
    public final static List<File> getAncestors(File f) {
320
        final List<File> path = new ArrayList<File>();
321
        File currentF = f;
322
        while (currentF != null) {
323
            path.add(0, currentF);
324
            currentF = currentF.getParentFile();
325
        }
326
        return path;
327
    }
328
 
329
    public final static File addSuffix(File f, String suffix) {
330
        return new File(f.getParentFile(), f.getName() + suffix);
331
    }
332
 
333
    /**
334
     * Prepend a string to a suffix.
335
     *
336
     * @param f the file, e.g. "sample.xml".
337
     * @param toInsert the string to insert in the filename, e.g. "-sql".
338
     * @param suffix the suffix of <code>f</code>, e.g. ".xml".
339
     * @return a new file with <code>toInsert</code> prepended to <code>suffix</code>, e.g.
340
     *         "sample-sql.xml".
341
     */
342
    public final static File prependSuffix(File f, String toInsert, String suffix) {
343
        return new File(f.getParentFile(), removeSuffix(f.getName(), suffix) + toInsert + suffix);
344
    }
345
 
144 ilm 346
    /**
347
     * Prepend a string to a suffix.
348
     *
349
     * @param f the file, e.g. "sample.xml".
350
     * @param toInsert the string to insert in the filename, e.g. "-sql".
351
     * @param suffix the suffix of <code>f</code>, e.g. ".xml".
352
     * @return a new file with <code>toInsert</code> prepended to <code>suffix</code>, e.g.
353
     *         "sample-sql.xml".
354
     */
355
    public final static Path prependSuffix(Path f, String toInsert, String suffix) {
356
        return f.resolveSibling(removeSuffix(f.getFileName().toString(), suffix) + toInsert + suffix);
357
    }
358
 
17 ilm 359
    public final static String removeSuffix(String name, String suffix) {
360
        return name.endsWith(suffix) ? name.substring(0, name.length() - suffix.length()) : name;
361
    }
362
 
363
    /**
364
     * Rename a file if necessary by finding a free name. The tested names are
365
     * <code>name + "_" + i + suffix</code>.
366
     *
367
     * @param parent the directory.
368
     * @param name the base name of the file.
369
     * @param suffix the suffix of the file, e.g. ".ods".
370
     * @return <code>new File(parent, name + suffix)</code> (always non existing) and the new file,
371
     *         (or <code>null</code> if no file was moved).
372
     */
373
    public final static File[] mvOut(final File parent, final String name, final String suffix) {
374
        final File fDest = new File(parent, name + suffix);
375
        final File renamed;
376
        if (fDest.exists()) {
377
            int i = 0;
378
            File free = fDest;
379
            while (free.exists()) {
380
                free = new File(parent, name + "_" + i + suffix);
381
                i++;
382
            }
383
            assert !fDest.equals(free);
384
            if (!fDest.renameTo(free))
385
                throw new IllegalStateException("Couldn't rename " + fDest + " to " + free);
386
            renamed = free;
387
        } else {
388
            renamed = null;
389
        }
390
        assert !fDest.exists();
391
        return new File[] { fDest, renamed };
392
    }
393
 
394
    // ** shell
395
 
396
    /**
397
     * Behave like the 'mv' unix utility, ie handle cross filesystems mv and <code>dest</code> being
398
     * a directory.
399
     *
400
     * @param f the source file.
401
     * @param dest the destination file or directory.
402
     * @return the error or <code>null</code> if there was none.
403
     */
404
    public static String mv(File f, File dest) {
405
        final File canonF;
406
        File canonDest;
407
        try {
408
            canonF = f.getCanonicalFile();
409
            canonDest = dest.getCanonicalFile();
410
        } catch (IOException e) {
411
            return ExceptionUtils.getStackTrace(e);
412
        }
413
        if (canonF.equals(canonDest))
414
            // nothing to do
415
            return null;
416
        if (canonDest.isDirectory())
417
            canonDest = new File(canonDest, canonF.getName());
418
 
419
        final File destF;
420
        if (canonDest.exists())
421
            return canonDest + " exists";
422
        else if (!canonDest.getParentFile().exists())
423
            return "parent of " + canonDest + " does not exist";
424
        else
425
            destF = canonDest;
426
        if (!canonF.renameTo(destF)) {
427
            try {
428
                copyDirectory(canonF, destF);
429
                if (destF.exists())
144 ilm 430
                    rm_R(canonF);
17 ilm 431
            } catch (IOException e) {
432
                return ExceptionUtils.getStackTrace(e);
433
            }
434
        }
435
        return null;
436
    }
437
 
438
    // transferTo() can be limited by a number of factors, like the number of bits of the system
439
    // if mmap is used (e.g. on Linux) or by an arbitrary magic number on Windows : 64Mb - 32Kb
440
    private static final int CHANNEL_MAX_COUNT = Math.min(64 * 1024 * 1024 - 32 * 1024, Integer.MAX_VALUE);
441
 
442
    public static void copyFile(File in, File out) throws IOException {
443
        copyFile(in, out, CHANNEL_MAX_COUNT);
444
    }
445
 
446
    /**
447
     * Copy a file. It is generally not advised to use 0 for <code>maxCount</code> since various
448
     * implementations have size limitations, see {@link #copyFile(File, File)}.
449
     *
450
     * @param in the source file.
451
     * @param out the destination file.
452
     * @param maxCount the number of bytes to copy at a time, 0 meaning size of <code>in</code>.
453
     * @throws IOException if an error occurs.
454
     */
455
    public static void copyFile(File in, File out, long maxCount) throws IOException {
149 ilm 456
        try (final FileInputStream sourceIn = new FileInputStream(in); final FileOutputStream sourceOut = new FileOutputStream(out);) {
83 ilm 457
            final FileChannel sourceChannel = sourceIn.getChannel();
17 ilm 458
            final long size = sourceChannel.size();
83 ilm 459
            if (maxCount == 0)
460
                maxCount = size;
461
            final FileChannel destinationChannel = sourceOut.getChannel();
17 ilm 462
            long position = 0;
463
            while (position < size) {
464
                position += sourceChannel.transferTo(position, maxCount, destinationChannel);
465
            }
466
        }
467
    }
468
 
25 ilm 469
    public static void copyFile(File in, File out, final boolean useTime) throws IOException {
470
        if (!useTime || in.lastModified() != out.lastModified()) {
471
            copyFile(in, out);
472
            if (useTime)
473
                out.setLastModified(in.lastModified());
474
        }
475
    }
476
 
17 ilm 477
    public static void copyDirectory(File in, File out) throws IOException {
478
        copyDirectory(in, out, Collections.<String> emptySet());
479
    }
480
 
481
    public static final Set<String> VersionControl = CollectionUtils.createSet(".svn", "CVS");
482
 
483
    public static void copyDirectory(File in, File out, final Set<String> toIgnore) throws IOException {
25 ilm 484
        copyDirectory(in, out, toIgnore, false);
485
    }
486
 
487
    public static void copyDirectory(File in, File out, final Set<String> toIgnore, final boolean useTime) throws IOException {
17 ilm 488
        if (toIgnore.contains(in.getName()))
489
            return;
490
 
491
        if (in.isDirectory()) {
492
            if (!out.exists()) {
493
                out.mkdir();
494
            }
495
 
496
            String[] children = in.list();
497
            for (int i = 0; i < children.length; i++) {
25 ilm 498
                copyDirectory(new File(in, children[i]), new File(out, children[i]), toIgnore, useTime);
17 ilm 499
            }
500
        } else {
501
            if (!in.getName().equals("Thumbs.db")) {
25 ilm 502
                copyFile(in, out, useTime);
17 ilm 503
            }
504
        }
505
    }
506
 
144 ilm 507
    public static void copyDirectory(Path in, Path out) throws IOException {
508
        copyDirectory(in, out, false);
509
    }
510
 
511
    public static void copyDirectory(Path in, Path out, final boolean hardLink, final CopyOption... copyOptions) throws IOException {
512
        copyDirectory(in, out, Collections.<String> emptySet(), hardLink, false, Arrays.asList(copyOptions));
513
    }
514
 
515
    public static void copyDirectory(Path in, Path out, final Set<String> toIgnore, final boolean hardLink, final boolean followLinks, final List<CopyOption> copyOptions) throws IOException {
516
        final LinkOption[] isDirOptions = followLinks ? new LinkOption[0] : new LinkOption[] { LinkOption.NOFOLLOW_LINKS };
517
        final Set<CopyOption> copyOptionsP = new HashSet<>(copyOptions);
518
        if (followLinks) {
519
            copyOptionsP.remove(LinkOption.NOFOLLOW_LINKS);
520
        } else {
521
            copyOptionsP.add(LinkOption.NOFOLLOW_LINKS);
522
        }
523
        copyDirectory(in, out, toIgnore, isDirOptions, copyOptionsP.toArray(new CopyOption[copyOptionsP.size()]), hardLink);
524
    }
525
 
526
    public static void copyDirectory(Path in, Path out, final Set<String> toIgnore, final LinkOption[] isDirOptions, final CopyOption[] copyOptions, final boolean hardLink) throws IOException {
527
        if (toIgnore.contains(in.getFileName().toString()))
528
            return;
529
 
530
        if (Files.isDirectory(in, isDirOptions)) {
531
            Files.copy(in, out, copyOptions);
532
 
533
            try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(in)) {
534
                for (final Path child : dirStream) {
535
                    copyDirectory(child, out.resolve(child.getFileName()), toIgnore, isDirOptions, copyOptions, hardLink);
536
                }
537
            }
538
            // fix up modification time of directory when done
539
            // (other attributes have already been copied at creation time)
540
            if (Arrays.asList(copyOptions).contains(StandardCopyOption.COPY_ATTRIBUTES))
541
                Files.setLastModifiedTime(out, Files.getLastModifiedTime(in));
542
        } else {
543
            if (!in.getFileName().toString().equals("Thumbs.db")) {
544
                if (hardLink)
545
                    Files.createLink(out, in);
546
                else
547
                    Files.copy(in, out, copyOptions);
548
            }
549
        }
550
    }
551
 
17 ilm 552
    /**
553
     * Delete recursively the passed directory. If a deletion fails, the method stops attempting to
554
     * delete and returns false.
555
     *
556
     * @param dir the dir to be deleted.
557
     * @return <code>true</code> if all deletions were successful.
144 ilm 558
     * @deprecated callers often forget to check return value, see also {@link #rm_R(Path)}
17 ilm 559
     */
560
    public static boolean rmR(File dir) {
561
        if (dir.isDirectory()) {
562
            File[] children = dir.listFiles();
563
            for (int i = 0; i < children.length; i++) {
564
                boolean success = rmR(children[i]);
565
 
566
                if (!success) {
567
 
568
                    return false;
569
                }
570
            }
571
        }
572
 
573
        // The directory is now empty so delete it
574
        return dir.delete();
575
    }
576
 
25 ilm 577
    public static void rm_R(File dir) throws IOException {
144 ilm 578
        rm_R(dir.toPath());
579
    }
580
 
581
    public static void rm_R(Path dir) throws IOException {
582
        rm_R(dir, false);
583
    }
584
 
585
    /**
586
     * Delete recursively the passed file.
587
     *
588
     * @param dir the file to delete.
589
     * @param mustExist what to do if <code>dir</code> is missing : <code>false</code> if it is not
590
     *        an error, <code>true</code> to fail.
591
     * @throws IOException if a deletion fails.
592
     */
593
    public static void rm_R(final Path dir, final boolean mustExist) throws IOException {
594
        if (!mustExist && !Files.exists(dir))
595
            return;
596
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
597
            @Override
598
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
599
                Files.delete(file);
600
                return FileVisitResult.CONTINUE;
25 ilm 601
            }
144 ilm 602
 
603
            @Override
604
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
605
                // The directory is now empty so delete it
606
                Files.delete(dir);
607
                return FileVisitResult.CONTINUE;
608
            }
609
        });
25 ilm 610
    }
611
 
612
    public static void rm(File f) throws IOException {
613
        if (f.exists() && !f.delete())
614
            throw new IOException("cannot delete " + f);
615
    }
616
 
17 ilm 617
    public static final File mkdir_p(File dir) throws IOException {
618
        if (!dir.exists()) {
619
            if (!dir.mkdirs()) {
620
                throw new IOException("cannot create directory " + dir);
621
            }
622
        }
623
        return dir;
624
    }
625
 
626
    /**
627
     * Create all ancestors of <code>f</code>.
628
     *
629
     * @param f any file whose ancestors should be created.
630
     * @return <code>f</code>.
631
     * @throws IOException if ancestors cannot be created.
632
     */
633
    public static final File mkParentDirs(File f) throws IOException {
634
        final File parentFile = f.getParentFile();
635
        if (parentFile != null)
636
            mkdir_p(parentFile);
637
        return f;
638
    }
639
 
640
    // **io
641
 
642
    /**
643
     * Read a file line by line with the default encoding and returns the concatenation of these.
644
     *
645
     * @param f the file to read.
646
     * @return the content of f.
647
     * @throws IOException if a pb occur while reading.
648
     */
649
    public static final String read(File f) throws IOException {
83 ilm 650
        return read(new InputStreamReader(new FileInputStream(f)));
17 ilm 651
    }
652
 
653
    /**
654
     * Read a file line by line and returns the concatenation of these.
655
     *
656
     * @param f the file to read.
83 ilm 657
     * @param charset the encoding of <code>f</code>.
17 ilm 658
     * @return the content of f.
659
     * @throws IOException if a pb occur while reading.
660
     */
661
    public static final String read(File f, String charset) throws IOException {
83 ilm 662
        return read(new InputStreamReader(new FileInputStream(f), charset));
663
    }
664
 
665
    public static final String readUTF8(File f) throws IOException {
666
        return readUTF8(new FileInputStream(f));
667
    }
668
 
156 ilm 669
    public static final String readUTF8(Path p) throws IOException {
670
        return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
671
    }
672
 
83 ilm 673
    public static final String readUTF8(InputStream ins) throws IOException {
674
        return read(ins, StringUtils.UTF8);
675
    }
676
 
677
    public static final String read(File f, Charset charset) throws IOException {
17 ilm 678
        return read(new FileInputStream(f), charset);
679
    }
680
 
83 ilm 681
    public static final String read(InputStream ins, Charset charset) throws IOException {
17 ilm 682
        final Reader reader;
683
        if (charset == null)
684
            reader = new InputStreamReader(ins);
685
        else
686
            reader = new InputStreamReader(ins, charset);
687
        return read(reader);
688
    }
689
 
690
    public static final String read(final Reader reader) throws IOException {
691
        return read(reader, 8192);
692
    }
693
 
694
    public static final String read(final Reader reader, final int bufferSize) throws IOException {
695
        final StringBuilder sb = new StringBuilder();
696
        final char[] buffer = new char[bufferSize];
697
        final BufferedReader in = new BufferedReader(reader);
698
        try {
699
            while (true) {
700
                final int count = in.read(buffer);
701
                if (count == -1)
702
                    break;
703
                sb.append(buffer, 0, count);
704
            }
705
        } finally {
706
            in.close();
707
        }
708
        return sb.toString();
709
    }
710
 
711
    /**
712
     * Read the whole content of a file.
713
     *
714
     * @param f the file to read.
715
     * @return its content.
716
     * @throws IOException if a pb occur while reading.
144 ilm 717
     * @see Files#readAllBytes(java.nio.file.Path)
17 ilm 718
     */
719
    public static final byte[] readBytes(File f) throws IOException {
144 ilm 720
        // works for /proc files which report 0 size
721
        return Files.readAllBytes(f.toPath());
17 ilm 722
    }
723
 
180 ilm 724
    /**
725
     * Write the passed string with default charset to the passed file, truncating it.
726
     *
727
     * @param s the string.
728
     * @param f the file.
729
     * @throws IOException if an error occurs.
730
     * @deprecated use {@link #writeUTF8(Path, String, OpenOption...)} or
731
     *             {@link #write2Step(String, Path)}
732
     */
17 ilm 733
    public static void write(String s, File f) throws IOException {
180 ilm 734
        write2Step(s, f, Charset.defaultCharset(), false);
17 ilm 735
    }
736
 
180 ilm 737
    public static void writeUTF8(String s, File f) throws IOException {
738
        writeUTF8(f.toPath(), s);
739
    }
740
 
741
    public static void writeUTF8(Path path, String s, OpenOption... options) throws IOException {
742
        Files.write(path, s.getBytes(StandardCharsets.UTF_8), options);
743
    }
744
 
745
    public static void write2Step(String s, File f, Charset charset, boolean append) throws IOException {
746
        write2Step(s, f.toPath(), charset, append);
747
    }
748
 
749
    public static void write2Step(final String s, final Path f) throws IOException {
750
        // UTF_8 default like Files.newBufferedReader()
751
        write2Step(s, f, StandardCharsets.UTF_8);
752
    }
753
 
754
    public static void write2Step(final String s, final Path f, final Charset charset) throws IOException {
755
        write2Step(s, f, charset, false);
756
    }
757
 
758
    public static void write2Step(final String s, final Path f, final Charset charset, final boolean append) throws IOException {
759
        // create temporary file in the same directory so we can move it
760
        final Path tmpFile = Files.createTempFile(f.toAbsolutePath().getParent(), null, null);
761
        try {
762
            // 1. write elsewhere
763
            final byte[] bs = charset == null ? s.getBytes() : s.getBytes(charset);
764
            if (append) {
765
                // REPLACE_EXISTING since tmpFile exists
766
                Files.copy(f, tmpFile, StandardCopyOption.REPLACE_EXISTING);
767
                Files.write(tmpFile, bs, StandardOpenOption.APPEND);
768
            } else {
769
                Files.write(tmpFile, bs);
770
            }
771
            // 2. move into place (cannot use ATOMIC_MOVE because f might exists ; and we would need
772
            // to handle AtomicMoveNotSupportedException)
773
            Files.move(tmpFile, f, StandardCopyOption.REPLACE_EXISTING);
774
            // don't try to delete if move() successful
775
        } catch (RuntimeException | Error | IOException e) {
776
            try {
777
                Files.deleteIfExists(tmpFile);
778
            } catch (Exception e1) {
779
                e.addSuppressed(e1);
780
            }
781
            throw e;
17 ilm 782
        }
783
    }
784
 
785
    /**
67 ilm 786
     * Create a writer for the passed file, and write the XML declaration.
787
     *
788
     * @param f a file
789
     * @return a writer with the same encoding as the XML.
790
     * @throws IOException if an error occurs.
791
     * @see StreamUtils#createXMLWriter(java.io.OutputStream)
792
     */
793
    public static BufferedWriter createXMLWriter(final File f) throws IOException {
174 ilm 794
        FileUtils.mkParentDirs(f);
67 ilm 795
        final FileOutputStream outs = new FileOutputStream(f);
796
        try {
797
            return StreamUtils.createXMLWriter(outs);
798
        } catch (RuntimeException e) {
799
            outs.close();
800
            throw e;
801
        } catch (IOException e) {
802
            outs.close();
803
            throw e;
804
        }
805
    }
806
 
807
    /**
808
     * Create an UTF-8 buffered writer.
809
     *
810
     * @param f the file to write to.
811
     * @return a buffered writer.
812
     * @throws FileNotFoundException if the file cannot be opened.
813
     */
814
    public static BufferedWriter createWriter(final File f) throws FileNotFoundException {
815
        return createWriter(f, StringUtils.UTF8);
816
    }
817
 
818
    public static BufferedWriter createWriter(final File f, final Charset cs) throws FileNotFoundException {
819
        final FileOutputStream outs = new FileOutputStream(f);
820
        try {
821
            return new BufferedWriter(new OutputStreamWriter(outs, cs));
822
        } catch (RuntimeException e) {
823
            try {
824
                outs.close();
825
            } catch (IOException e1) {
826
                e1.printStackTrace();
827
            }
828
            throw e;
829
        }
830
    }
831
 
832
    /**
17 ilm 833
     * Execute the passed transformer with the lock on the passed file.
834
     *
835
     * @param <T> return type.
836
     * @param f the file to lock.
837
     * @param transf what to do on the file.
838
     * @return what <code>transf</code> returns.
144 ilm 839
     * @throws IOException if an error occurs while locking the file.
840
     * @throws X if an error occurs while using the file.
17 ilm 841
     */
144 ilm 842
    public static final <T, X extends Exception> T doWithLock(final File f, ExnTransformer<RandomAccessFile, T, X> transf) throws IOException, X {
843
        mkParentDirs(f);
17 ilm 844
        // don't use FileOutputStream : it truncates the file on creation
144 ilm 845
        // we need write to obtain lock
846
        try (final RandomAccessFile out = new RandomAccessFile(f, "rw")) {
17 ilm 847
            out.getChannel().lock();
144 ilm 848
            return transf.transformChecked(out);
17 ilm 849
        }
144 ilm 850
        // the lock is released on close()
17 ilm 851
    }
852
 
853
    private static final Map<URL, File> files = new HashMap<URL, File>();
854
 
855
    private static final File getShortCutFile() throws IOException {
856
        return getFile(FileUtils.class.getResource("shortcut.vbs"));
857
    }
858
 
859
    // windows cannot execute a string, it demands a file
860
    public static final File getFile(final URL url) throws IOException {
67 ilm 861
        // avoid unnecessary IO if already a file
862
        File urlFile = null;
863
        // inexpensive comparison before trying to convert to URI and call the File constructor
864
        if ("file".equalsIgnoreCase(url.getProtocol())) {
865
            try {
866
                urlFile = new File(url.toURI());
867
            } catch (Exception e) {
868
                Log.get().log(Level.FINER, "couldn't convert to file " + url, e);
869
            }
870
        }
871
        if (urlFile != null)
872
            return urlFile;
873
 
17 ilm 874
        final File shortcutFile;
875
        final File currentFile = files.get(url);
876
        if (currentFile == null || !currentFile.exists()) {
877
            shortcutFile = File.createTempFile("windowsIsLame", ".vbs");
67 ilm 878
            // ATTN if the VM is not terminated normally, the file won't be deleted
879
            // perhaps a thread to delete the file after a certain amount of time
17 ilm 880
            shortcutFile.deleteOnExit();
881
            files.put(url, shortcutFile);
149 ilm 882
            try (final InputStream stream = url.openStream(); final FileOutputStream out = new FileOutputStream(shortcutFile);) {
17 ilm 883
                StreamUtils.copy(stream, out);
884
            }
885
        } else
886
            shortcutFile = currentFile;
887
        return shortcutFile;
888
    }
889
 
890
    /**
891
     * Create a symbolic link from <code>link</code> to <code>target</code>.
892
     *
893
     * @param target the target of the link, eg ".".
894
     * @param link the file to create or replace, eg "l".
895
     * @return the link if the creation was successfull, <code>null</code> otherwise, eg "l.LNK".
896
     * @throws IOException if an error occurs.
897
     */
898
    public static final File ln(final File target, final File link) throws IOException {
899
        final Process ps;
900
        final File res;
80 ilm 901
        if (OSFamily.getInstance() == OSFamily.Windows) {
17 ilm 902
            // using the .vbs since it doesn't depends on cygwin
903
            // and cygwin's ln is weird :
904
            // 1. needs CYGWIN=winsymlinks to create a shortcut, but even then "ln -f" doesn't work
905
            // since it tries to delete l instead of l.LNK
906
            // 2. it sets the system flag so "dir" doesn't show the shortcut (unless you add /AS)
907
            // 3. the shortcut is recognized as a symlink thanks to a special attribute that can get
908
            // lost (e.g. copying in eclipse)
180 ilm 909
            ps = startDiscardingOutput("cscript", getShortCutFile().getAbsolutePath(), link.getAbsolutePath(), target.getCanonicalPath());
17 ilm 910
            res = new File(link.getParentFile(), link.getName() + ".LNK");
911
        } else {
912
            final String rel = FileUtils.relative(link.getAbsoluteFile().getParentFile(), target);
913
            // add -f to replace existing links
914
            // add -n so that ln -sf aDir anExistantLinkToIt succeed
915
            final String[] cmdarray = { "ln", "-sfn", rel, link.getAbsolutePath() };
180 ilm 916
            ps = startDiscardingOutput(cmdarray);
17 ilm 917
            res = link;
918
        }
919
        try {
920
            final int exitValue = ps.waitFor();
921
            if (exitValue == 0)
922
                return res;
923
            else
924
                throw new IOException("Abnormal exit value: " + exitValue);
925
        } catch (InterruptedException e) {
926
            throw ExceptionUtils.createExn(IOException.class, "interrupted", e);
927
        }
928
    }
929
 
930
    /**
931
     * Resolve a symbolic link or a windows shortcut.
932
     *
933
     * @param link the shortcut, e.g. shortcut.lnk.
934
     * @return the target of <code>link</code>, <code>null</code> if not found, e.g. target.txt.
935
     * @throws IOException if an error occurs.
936
     */
937
    public static final File readlink(final File link) throws IOException {
938
        final Process ps;
80 ilm 939
        if (OSFamily.getInstance() == OSFamily.Windows) {
17 ilm 940
            ps = Runtime.getRuntime().exec(new String[] { "cscript", "//NoLogo", getShortCutFile().getAbsolutePath(), link.getAbsolutePath() });
941
        } else {
942
            // add -f to canonicalize
943
            ps = Runtime.getRuntime().exec(new String[] { "readlink", "-f", link.getAbsolutePath() });
944
        }
945
        try {
83 ilm 946
            ps.getErrorStream().close();
149 ilm 947
            final String res;
948
            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(ps.getInputStream()));) {
949
                res = reader.readLine();
950
            }
17 ilm 951
            if (ps.waitFor() != 0 || res == null || res.length() == 0)
952
                return null;
953
            else
954
                return new File(res);
955
        } catch (InterruptedException e) {
956
            throw ExceptionUtils.createExn(IOException.class, "interrupted", e);
957
        }
958
    }
959
 
67 ilm 960
    // from guava/src/com/google/common/io/Files.java
961
    /** Maximum loop count when creating temp directories. */
962
    private static final int TEMP_DIR_ATTEMPTS = 10000;
963
 
17 ilm 964
    /**
67 ilm 965
     * Atomically creates a new directory somewhere beneath the system's temporary directory (as
966
     * defined by the {@code java.io.tmpdir} system property), and returns its name.
967
     *
968
     * <p>
969
     * Use this method instead of {@link File#createTempFile(String, String)} when you wish to
970
     * create a directory, not a regular file. A common pitfall is to call {@code createTempFile},
971
     * delete the file and create a directory in its place, but this leads a race condition which
972
     * can be exploited to create security vulnerabilities, especially when executable files are to
973
     * be written into the directory.
974
     *
975
     * <p>
976
     * This method assumes that the temporary volume is writable, has free inodes and free blocks,
977
     * and that it will not be called thousands of times per second.
978
     *
979
     * @param prefix the prefix string to be used in generating the directory's name.
980
     * @return the newly-created directory.
981
     * @throws IllegalStateException if the directory could not be created.
180 ilm 982
     * @deprecated use
983
     *             {@link Files#createTempDirectory(String, java.nio.file.attribute.FileAttribute...)}
67 ilm 984
     */
985
    public static File createTempDir(final String prefix) {
986
        final File baseDir = new File(System.getProperty("java.io.tmpdir"));
987
        final String baseName = prefix + System.currentTimeMillis() + "-";
988
 
989
        for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
990
            final File tempDir = new File(baseDir, baseName + counter);
991
            if (tempDir.mkdir()) {
992
                return tempDir;
993
            }
994
        }
995
        throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
996
    }
997
 
998
    /**
17 ilm 999
     * Tries to open the passed file as if it were graphically opened by the current user (respect
1000
     * user's "open with"). If a native way to open the file can't be found, tries the passed list
1001
     * of executables.
1002
     *
1003
     * @param f the file to open.
1004
     * @param executables a list of executables to try, e.g. ["ooffice", "soffice"].
1005
     * @throws IOException if the file can't be opened.
1006
     */
1007
    public static final void open(File f, String[] executables) throws IOException {
156 ilm 1008
        if (!f.exists()) {
1009
            throw new FileNotFoundException(f.getAbsolutePath() + " not found");
1010
        }
17 ilm 1011
        try {
1012
            openNative(f);
1013
        } catch (IOException exn) {
1014
            for (int i = 0; i < executables.length; i++) {
1015
                final String executable = executables[i];
1016
                try {
180 ilm 1017
                    startDiscardingOutput(executable, f.getCanonicalPath());
17 ilm 1018
                    return;
1019
                } catch (IOException e) {
180 ilm 1020
                    exn.addSuppressed(new IOException("unable to open with " + executable, e));
17 ilm 1021
                    // try the next one
1022
                }
1023
            }
180 ilm 1024
            throw new IOException("unable to open " + f, exn);
17 ilm 1025
        }
1026
    }
1027
 
1028
    /**
1029
     * Open the passed file as if it were graphically opened by the current user (user's "open
1030
     * with").
1031
     *
1032
     * @param f the file to open.
1033
     * @throws IOException if f couldn't be opened.
1034
     */
1035
    private static final void openNative(File f) throws IOException {
180 ilm 1036
        openNative(f.getCanonicalPath());
1037
    }
1038
 
1039
    private static final void openNative(URI uri) throws IOException {
1040
        openNative(uri.toASCIIString());
1041
    }
1042
 
1043
    private static final void openNative(String param) throws IOException {
80 ilm 1044
        final OSFamily os = OSFamily.getInstance();
17 ilm 1045
        final String[] cmdarray;
80 ilm 1046
        if (os == OSFamily.Windows) {
180 ilm 1047
            cmdarray = new String[] { "cmd", "/c", "start", "\"\"", param };
80 ilm 1048
        } else if (os == OSFamily.Mac) {
180 ilm 1049
            cmdarray = new String[] { "open", param };
80 ilm 1050
        } else if (os instanceof Unix) {
180 ilm 1051
            cmdarray = new String[] { "xdg-open", param };
17 ilm 1052
        } else {
180 ilm 1053
            throw new IOException("unknown way to open " + param);
17 ilm 1054
        }
1055
        try {
180 ilm 1056
            final Process ps = startDiscardingOutput(cmdarray);
17 ilm 1057
            // can wait since the command return as soon as the native application is launched
1058
            // (i.e. this won't wait 30s for OpenOffice)
83 ilm 1059
            final int res = ps.waitFor();
17 ilm 1060
            if (res != 0)
1061
                throw new IOException("error (" + res + ") executing " + Arrays.asList(cmdarray));
1062
        } catch (InterruptedException e) {
1063
            throw ExceptionUtils.createExn(IOException.class, "interrupted waiting for " + Arrays.asList(cmdarray), e);
1064
        }
1065
    }
1066
 
180 ilm 1067
    private static final Process startDiscardingOutput(final String... command) throws IOException {
1068
        return startDiscardingOutput(new ProcessBuilder(command));
1069
    }
1070
 
1071
    private static final Process startDiscardingOutput(final ProcessBuilder pb) throws IOException {
1072
        final Process res = pb.redirectOutput(ProcessStreams.DISCARD).redirectError(ProcessStreams.DISCARD).start();
1073
        res.getOutputStream().close();
1074
        return res;
1075
    }
1076
 
17 ilm 1077
    static final boolean gnomeRunning() {
1078
        try {
180 ilm 1079
            final Process ps = startDiscardingOutput("pgrep", "-u", System.getProperty("user.name"), "nautilus");
83 ilm 1080
            // no need for output, use exit status
1081
            return ps.waitFor() == 0;
17 ilm 1082
        } catch (Exception e) {
1083
            return false;
1084
        }
1085
    }
1086
 
73 ilm 1087
    public static final String XML_TYPE = "text/xml";
17 ilm 1088
    private static final Map<String, String> ext2mime;
83 ilm 1089
    private static final SetMap<String, String> mime2ext;
1090
 
17 ilm 1091
    static {
83 ilm 1092
        mime2ext = new SetMap<String, String>(Mode.NULL_FORBIDDEN);
1093
        mime2ext.putCollection(XML_TYPE, ".xml");
1094
        mime2ext.putCollection("image/jpeg", ".jpg", ".jpeg");
1095
        mime2ext.putCollection("image/png", ".png");
1096
        mime2ext.putCollection("image/tiff", ".tiff", ".tif");
1097
        mime2ext.putCollection("application/pdf", ".pdf");
1098
 
1099
        mime2ext.putCollection("application/vnd.oasis.opendocument.spreadsheet", ".ods");
1100
        mime2ext.putCollection("application/vnd.oasis.opendocument.text", ".odt");
1101
        mime2ext.putCollection("application/vnd.oasis.opendocument.presentation", ".odp");
1102
        mime2ext.putCollection("application/vnd.oasis.opendocument.graphics", ".odg");
1103
 
17 ilm 1104
        ext2mime = new HashMap<String, String>();
83 ilm 1105
        for (final Entry<String, Set<String>> e : mime2ext.entrySet()) {
1106
            final String m = e.getKey();
1107
            for (final String ext : e.getValue()) {
1108
                if (ext2mime.put(ext, m) != null)
1109
                    Log.get().info("Duplicate extension : " + ext);
1110
            }
1111
        }
17 ilm 1112
    }
1113
 
1114
    /**
142 ilm 1115
     * Try to guess the media type of the passed file name (see
1116
     * <a href="http://www.iana.org/assignments/media-types">iana</a>).
17 ilm 1117
     *
1118
     * @param fname a file name.
1119
     * @return its mime type.
1120
     */
1121
    public static final String findMimeType(String fname) {
1122
        for (final Map.Entry<String, String> e : ext2mime.entrySet()) {
1123
            if (fname.toLowerCase().endsWith(e.getKey()))
1124
                return e.getValue();
1125
        }
1126
        return null;
1127
    }
1128
 
83 ilm 1129
    public static final Set<String> getExtensionsFromMimeType(final String mimetype) {
1130
        return mime2ext.get(mimetype);
1131
    }
1132
 
17 ilm 1133
    /**
57 ilm 1134
     * Return the string after the last dot.
1135
     *
1136
     * @param fname a name, e.g. "test.odt" or "sans".
1137
     * @return the extension, e.g. "odt" or <code>null</code>.
1138
     */
1139
    public static final String getExtension(String fname) {
83 ilm 1140
        return getExtension(fname, false);
1141
    }
1142
 
1143
    public static final String getExtension(final String fname, final boolean withDot) {
57 ilm 1144
        final int lastIndex = fname.lastIndexOf('.');
83 ilm 1145
        return lastIndex < 0 ? null : fname.substring(lastIndex + (withDot ? 0 : 1));
57 ilm 1146
    }
1147
 
1148
    /**
17 ilm 1149
     * Chars not valid in filenames.
1150
     */
1151
    public static final Collection<Character> INVALID_CHARS;
1152
 
1153
    /**
1154
     * An escaper suitable for producing valid filenames.
1155
     */
1156
    public static final Escaper FILENAME_ESCAPER = new StringUtils.Escaper('\'', 'Q');
73 ilm 1157
 
142 ilm 1158
    static private final String WS = "\\p{javaWhitespace}";
1159
    static private final Pattern WS_PATTERN = Pattern.compile(WS + "+");
1160
    static private final Pattern CONTROL_PATTERN = Pattern.compile("[\\p{IsCc}\\p{IsCf}&&[^" + WS + "]]+");
73 ilm 1161
    static private final Pattern INVALID_CHARS_PATTERN;
1162
 
17 ilm 1163
    static {
1164
        // from windows explorer
73 ilm 1165
        // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
1166
        // Naming Files, Paths, and Namespaces
1167
        // on Mac only '/' and ':', on Linux only '/'
17 ilm 1168
        FILENAME_ESCAPER.add('"', 'D').add(':', 'C').add('/', 'S').add('\\', 'A');
1169
        FILENAME_ESCAPER.add('<', 'L').add('>', 'G').add('*', 'R').add('|', 'P').add('?', 'M');
1170
        INVALID_CHARS = FILENAME_ESCAPER.getEscapedChars();
73 ilm 1171
        INVALID_CHARS_PATTERN = Pattern.compile("[" + CollectionUtils.join(INVALID_CHARS, "") + "]");
17 ilm 1172
    }
1173
 
73 ilm 1174
    /**
1175
     * Sanitize a name. Remove control characters, trim, and replace {@link #INVALID_CHARS} by '_'.
1176
     *
1177
     * @param name an arbitrary name.
1178
     * @return a name suitable for any file system.
1179
     */
1180
    static public final String sanitize(String name) {
142 ilm 1181
        // remove control and format characters (except white spaces)
73 ilm 1182
        name = CONTROL_PATTERN.matcher(name).replaceAll("");
142 ilm 1183
        // only use one regular space (must be done after removing control characters as if they are
1184
        // between spaces we want only one space to remain)
73 ilm 1185
        name = WS_PATTERN.matcher(name).replaceAll(" ");
1186
        // leading and trailing spaces are hard to see (and illegal in Explorer)
1187
        name = name.trim();
1188
 
1189
        // replace all invalid characters with _
1190
        name = INVALID_CHARS_PATTERN.matcher(name).replaceAll("_");
1191
 
1192
        return name;
1193
    }
1194
 
17 ilm 1195
    public static final FileFilter DIR_FILTER = new FileFilter() {
1196
        @Override
1197
        public boolean accept(File f) {
1198
            return f.isDirectory();
1199
        }
1200
    };
1201
    public static final FileFilter REGULAR_FILE_FILTER = new FileFilter() {
1202
        @Override
1203
        public boolean accept(File f) {
1204
            return f.isFile();
1205
        }
1206
    };
144 ilm 1207
    public static final Filter<Path> DIR_PATH_FILTER = new DirectoryStream.Filter<Path>() {
1208
        @Override
1209
        public boolean accept(Path entry) throws IOException {
1210
            return Files.isDirectory(entry, LinkOption.NOFOLLOW_LINKS);
1211
        }
1212
    };
17 ilm 1213
 
1214
    /**
1215
     * Return a filter that select regular files ending in <code>ext</code>.
1216
     *
1217
     * @param ext the end of the name, eg ".xml".
1218
     * @return the corresponding filter.
1219
     */
1220
    public static final FileFilter createEndFileFilter(final String ext) {
1221
        return new FileFilter() {
1222
            @Override
1223
            public boolean accept(File f) {
1224
                return f.isFile() && f.getName().endsWith(ext);
1225
            }
1226
        };
1227
    }
144 ilm 1228
 
1229
    /**
1230
     * How to merge the group and others portion of permissions for non-POSIX FS.
1231
     *
1232
     * @author sylvain
1233
     * @see FileUtils#setFilePermissionsFromPOSIX(File, String, GroupAndOthers)
1234
     */
1235
    public static enum GroupAndOthers {
1236
        REQUIRE_SAME {
1237
            @Override
1238
            protected Set<Permission> getNonEqual(Set<Permission> groupPerms, Set<Permission> otherPerms) {
1239
                throw new IllegalArgumentException("Different permissions : " + groupPerms + " != " + otherPerms);
1240
            }
1241
        },
1242
        PERMISSIVE {
1243
            @Override
1244
            protected Set<Permission> getNonEqual(Set<Permission> groupPerms, Set<Permission> otherPerms) {
1245
                final EnumSet<Permission> res = EnumSet.noneOf(Permission.class);
1246
                res.addAll(groupPerms);
1247
                res.addAll(otherPerms);
1248
                return res;
1249
            }
1250
        },
1251
        OTHERS {
1252
            @Override
1253
            protected Set<Permission> getNonEqual(Set<Permission> groupPerms, Set<Permission> otherPerms) {
1254
                return otherPerms;
1255
            }
1256
        },
1257
        RESTRICTIVE {
1258
            @Override
1259
            protected Set<Permission> getNonEqual(Set<Permission> groupPerms, Set<Permission> otherPerms) {
1260
                final EnumSet<Permission> res = EnumSet.allOf(Permission.class);
1261
                res.retainAll(groupPerms);
1262
                res.retainAll(otherPerms);
1263
                return res;
1264
            }
1265
        };
1266
 
1267
        public final Set<Permission> getPermissions(final Set<Permission> groupPerms, final Set<Permission> otherPerms) {
1268
            if (groupPerms.equals(otherPerms)) {
1269
                return groupPerms;
1270
            } else {
1271
                return getNonEqual(groupPerms, otherPerms);
1272
            }
1273
        }
1274
 
1275
        public final Set<Permission> getPermissions(final String posixPerms) {
1276
            final Set<Permission> groupPerms = Permission.fromString(posixPerms.substring(3, 6));
1277
            final Set<Permission> otherPerms = Permission.fromString(posixPerms.substring(6, 9));
1278
            return this.getPermissions(groupPerms, otherPerms);
1279
        }
1280
 
1281
        protected abstract Set<Permission> getNonEqual(final Set<Permission> groupPerms, final Set<Permission> otherPerms);
1282
 
1283
    }
1284
 
1285
    public static final String setPermissions(final Path p, final String posixPerms) throws IOException {
1286
        return setPermissions(p, posixPerms, GroupAndOthers.RESTRICTIVE);
1287
    }
1288
 
1289
    /**
1290
     * Use {@link PosixFileAttributeView#setPermissions(Set)} if possible, otherwise use
1291
     * {@link #setFilePermissionsFromPOSIX(File, String, GroupAndOthers)}.
1292
     *
1293
     * @param p the path to change.
1294
     * @param posixPerms the new permissions to apply.
1295
     * @param groupAndOthers only for non-POSIX FS, how to merge group and others portion.
1296
     * @return the permission applied, 9 characters for POSIX, 6 for non-POSIX (i.e. 3 for owner, 3
1297
     *         for the rest), <code>null</code> if some permissions couldn't be applied (only on
1298
     *         non-POSIX).
1299
     * @throws IOException if permissions couldn't be applied.
1300
     */
1301
    public static final String setPermissions(final Path p, final String posixPerms, final GroupAndOthers groupAndOthers) throws IOException {
1302
        final String res;
1303
        final PosixFileAttributeView view = Files.getFileAttributeView(p, PosixFileAttributeView.class);
1304
        if (view != null) {
1305
            view.setPermissions(PosixFilePermissions.fromString(posixPerms));
1306
            res = posixPerms;
1307
        } else {
1308
            // final Set<Permission> notOwnerPerms = setFilePermissions(p.toFile(), pfp,
1309
            // groupAndOthers);
1310
            final Set<Permission> notOwnerPerms = setFilePermissionsFromPOSIX(p.toFile(), posixPerms, groupAndOthers);
1311
            res = notOwnerPerms == null ? null : posixPerms.substring(0, 3) + Permission.get3chars(notOwnerPerms);
1312
        }
1313
        return res;
1314
    }
1315
 
1316
    public static final Set<Permission> setFilePermissionsFromPOSIX(final File f, final String posixPerms) {
1317
        return setFilePermissionsFromPOSIX(f, posixPerms, GroupAndOthers.RESTRICTIVE);
1318
    }
1319
 
1320
    /**
1321
     * This method doesn't need POSIX but must merge permissions before applying them.
1322
     *
1323
     * @param f the file to change.
1324
     * @param posixPerms the POSIX permissions to merge.
1325
     * @param groupAndOthers how to merge.
1326
     * @return the merged permissions for the "not owner" portion, or <code>null</code> if some
1327
     *         permissions couldn't be set.
1328
     * @see #setFilePermissions(File, Set, Set)
1329
     */
1330
    public static final Set<Permission> setFilePermissionsFromPOSIX(final File f, final String posixPerms, final GroupAndOthers groupAndOthers) {
1331
        if (posixPerms.length() != 9)
1332
            throw new IllegalArgumentException("Invalid mode : " + posixPerms);
1333
        final Set<Permission> ownerPerms = Permission.fromString(posixPerms.substring(0, 3));
1334
        final Set<Permission> notOwnerPerms = groupAndOthers.getPermissions(posixPerms);
1335
        assert notOwnerPerms != null;
1336
        final boolean success = setFilePermissions(f, ownerPerms, notOwnerPerms);
1337
        return success ? notOwnerPerms : null;
1338
    }
1339
 
1340
    /**
1341
     * Use {@link File} methods to set permissions. This works everywhere but group and others are
1342
     * treated as the same.
1343
     *
1344
     * @param f the file to change.
1345
     * @param owner the permissions for the owner.
1346
     * @param notOwner the permissions for not the owner.
1347
     * @return <code>true</code> if all asked permissions were set.
1348
     * @see File#setReadable(boolean, boolean)
1349
     * @see File#setWritable(boolean, boolean)
1350
     * @see File#setExecutable(boolean, boolean)
1351
     */
1352
    public static final boolean setFilePermissions(final File f, final Set<Permission> owner, final Set<Permission> notOwner) {
1353
        boolean res = setFilePermissions(f, notOwner, false);
1354
        if (!owner.equals(notOwner)) {
1355
            res &= setFilePermissions(f, owner, true);
1356
        }
1357
        return res;
1358
    }
1359
 
1360
    public static final boolean setFilePermissions(final File f, final Set<Permission> perms, final boolean ownerOnly) {
1361
        boolean res = f.setReadable(perms.contains(Permission.READ), ownerOnly);
1362
        res &= f.setWritable(perms.contains(Permission.WRITE), ownerOnly);
1363
        res &= f.setExecutable(perms.contains(Permission.EXECUTE), ownerOnly);
1364
        return res;
1365
    }
1366
 
1367
    public static enum Permission {
1368
        READ, WRITE, EXECUTE;
1369
 
1370
        public static final Permission R = READ;
1371
        public static final Permission W = WRITE;
1372
        public static final Permission X = EXECUTE;
1373
        public static final Map<String, Set<Permission>> FROM_STRING = new HashMap<>();
1374
        public static final Pattern MINUS_PATTERN = Pattern.compile("-+");
1375
        static {
1376
            putString("---", Collections.<Permission> emptySet());
1377
            putString("--x", Collections.singleton(EXECUTE));
1378
            putString("-w-", Collections.singleton(WRITE));
1379
            putString("-wx", EnumSet.of(WRITE, EXECUTE));
1380
            putString("r--", Collections.singleton(READ));
1381
            putString("r-x", EnumSet.of(READ, EXECUTE));
1382
            putString("rw-", EnumSet.of(READ, WRITE));
1383
            putString("rwx", EnumSet.allOf(Permission.class));
1384
        }
1385
 
1386
        static private final void putString(final String str, final EnumSet<Permission> set) {
1387
            putString(str, Collections.unmodifiableSet(set));
1388
        }
1389
 
1390
        static private final void putString(final String str, final Set<Permission> unmodifiableSet) {
1391
            FROM_STRING.put(str, unmodifiableSet);
1392
            FROM_STRING.put(MINUS_PATTERN.matcher(str).replaceAll(""), unmodifiableSet);
1393
        }
1394
 
1395
        static public final Set<Permission> fromString(final String str) {
1396
            final Set<Permission> res = FROM_STRING.get(str);
1397
            if (res == null)
1398
                throw new IllegalArgumentException("Invalid string : " + str);
1399
            return res;
1400
        }
1401
 
1402
        public static final String get3chars(final Set<Permission> perms) {
1403
            return get3chars(perms.contains(READ), perms.contains(WRITE), perms.contains(EXECUTE));
1404
        }
1405
 
1406
        private static final String get3chars(final boolean read, final boolean write, final boolean exec) {
1407
            final StringBuilder sb = new StringBuilder(3);
1408
            sb.append(read ? 'r' : '-');
1409
            sb.append(write ? 'w' : '-');
1410
            sb.append(exec ? 'x' : '-');
1411
            return sb.toString();
1412
        }
1413
    }
17 ilm 1414
}