OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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