aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/apache/commons/io/DirectoryWalkerTestCaseJava4.java
blob: ad7337dddd765fce6e3dcec18f1c40de7f1b1b69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.io;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
import org.junit.jupiter.api.Test;

/**
 * This is used to test DirectoryWalker for correctness when using Java4 (i.e. no generics).
 *
 * @see DirectoryWalker
 */
@SuppressWarnings({"unchecked", "rawtypes"}) // Java4
public class DirectoryWalkerTestCaseJava4 {

    /**
     * Test DirectoryWalker implementation that finds files in a directory hierarchy
     * applying a file filter.
     */
    static class TestCancelWalker extends DirectoryWalker {
        private final String cancelFileName;
        private final boolean suppressCancel;

        TestCancelWalker(final String cancelFileName, final boolean suppressCancel) {
            this.cancelFileName = cancelFileName;
            this.suppressCancel = suppressCancel;
        }

        /**
         * find files.
         */
        protected List find(final File startDirectory) throws IOException {
            final List results = new ArrayList();
            walk(startDirectory, results);
            return results;
        }

        /**
         * Handles Cancel.
         */
        @Override
        protected void handleCancelled(final File startDirectory, final Collection results,
                                       final CancelException cancel) throws IOException {
            if (!suppressCancel) {
                super.handleCancelled(startDirectory, results, cancel);
            }
        }

        /**
         * Handles a directory end by adding the File to the result set.
         */
        @Override
        protected void handleDirectoryEnd(final File directory, final int depth, final Collection results) throws IOException {
            results.add(directory);
            if (cancelFileName.equals(directory.getName())) {
                throw new CancelException(directory, depth);
            }
        }

        /**
         * Handles a file by adding the File to the result set.
         */
        @Override
        protected void handleFile(final File file, final int depth, final Collection results) throws IOException {
            results.add(file);
            if (cancelFileName.equals(file.getName())) {
                throw new CancelException(file, depth);
            }
        }
    }
    /**
     * Test DirectoryWalker implementation that always returns false
     * from handleDirectoryStart()
     */
    private static final class TestFalseFileFinder extends TestFileFinder {

        protected TestFalseFileFinder(final FileFilter filter, final int depthLimit) {
            super(filter, depthLimit);
        }

        /**
         * Always returns false.
         */
        @Override
        protected boolean handleDirectory(final File directory, final int depth, final Collection results) {
            return false;
        }
    }
    /**
     * Test DirectoryWalker implementation that finds files in a directory hierarchy
     * applying a file filter.
     */
    private static class TestFileFinder extends DirectoryWalker {

        protected TestFileFinder(final FileFilter filter, final int depthLimit) {
            super(filter, depthLimit);
        }

        protected TestFileFinder(final IOFileFilter dirFilter, final IOFileFilter fileFilter, final int depthLimit) {
            super(dirFilter, fileFilter, depthLimit);
        }

        /**
         * find files.
         */
        protected List<File> find(final File startDirectory) {
            final List<File> results = new ArrayList<>();
            try {
                walk(startDirectory, results);
            } catch (final IOException ex) {
                fail(ex.toString());
            }
            return results;
        }

        /**
         * Handles a directory end by adding the File to the result set.
         */
        @Override
        protected void handleDirectoryEnd(final File directory, final int depth, final Collection results) {
            results.add(directory);
        }

        /**
         * Handles a file by adding the File to the result set.
         */
        @Override
        protected void handleFile(final File file, final int depth, final Collection results) {
            results.add(file);
        }
    }
    /**
     * Test DirectoryWalker implementation that finds files in a directory hierarchy
     * applying a file filter.
     */
    static class TestMultiThreadCancelWalker extends DirectoryWalker {
        private final String cancelFileName;
        private final boolean suppressCancel;
        private boolean cancelled;
        public List results;

        TestMultiThreadCancelWalker(final String cancelFileName, final boolean suppressCancel) {
            this.cancelFileName = cancelFileName;
            this.suppressCancel = suppressCancel;
        }

        /**
         * find files.
         */
        protected List find(final File startDirectory) throws IOException {
            results = new ArrayList();
            walk(startDirectory, results);
            return results;
        }

        /**
         * Handles Cancel.
         */
        @Override
        protected void handleCancelled(final File startDirectory, final Collection results,
                                       final CancelException cancel) throws IOException {
            if (!suppressCancel) {
                super.handleCancelled(startDirectory, results, cancel);
            }
        }

        /**
         * Handles a directory end by adding the File to the result set.
         */
        @Override
        protected void handleDirectoryEnd(final File directory, final int depth, final Collection results) throws IOException {
            results.add(directory);
            assertFalse(cancelled);
            if (cancelFileName.equals(directory.getName())) {
                cancelled = true;
            }
        }

        /**
         * Handles a file by adding the File to the result set.
         */
        @Override
        protected void handleFile(final File file, final int depth, final Collection results) throws IOException {
            results.add(file);
            assertFalse(cancelled);
            if (cancelFileName.equals(file.getName())) {
                cancelled = true;
            }
        }

        /**
         * Handles Cancelled.
         */
        @Override
        protected boolean handleIsCancelled(final File file, final int depth, final Collection results) throws IOException {
            return cancelled;
        }
    }
    // Directories
    private static final File current = FileUtils.current();
    private static final File javaDir = new File("src/main/java");
    private static final File orgDir = new File(javaDir, "org");
    private static final File apacheDir = new File(orgDir, "apache");

    private static final File commonsDir = new File(apacheDir, "commons");
    private static final File ioDir = new File(commonsDir, "io");
    private static final File outputDir = new File(ioDir, "output");
    private static final File[] dirs = {orgDir, apacheDir, commonsDir, ioDir, outputDir};
    // Files
    private static final File fileNameUtils = new File(ioDir, "FilenameUtils.java");
    private static final File ioUtils = new File(ioDir, "IOUtils.java");

    private static final File proxyWriter = new File(outputDir, "ProxyWriter.java");
    private static final File nullStream = new File(outputDir, "NullOutputStream.java");
    private static final File[] ioFiles = {fileNameUtils, ioUtils};
    private static final File[] outputFiles = {proxyWriter, nullStream};
    // Filters
    private static final IOFileFilter dirsFilter = createNameFilter(dirs);

    private static final IOFileFilter ioFilesFilter = createNameFilter(ioFiles);


    private static final IOFileFilter outputFilesFilter = createNameFilter(outputFiles);

    private static final IOFileFilter ioDirAndFilesFilter = new OrFileFilter(dirsFilter, ioFilesFilter);

    private static final IOFileFilter dirsAndFilesFilter = new OrFileFilter(ioDirAndFilesFilter, outputFilesFilter);

    // Filter to exclude SVN files
    private static final IOFileFilter NOT_SVN = FileFilterUtils.makeSVNAware(null);

    /**
     * Create a name filter containing the names of the files
     * in the array.
     */
    private static IOFileFilter createNameFilter(final File[] files) {
        final String[] names = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            names[i] = files[i].getName();
        }
        return new NameFileFilter(names);
    }

    /**
     * Check the files in the array are in the results list.
     */
    private void checkContainsFiles(final String prefix, final File[] files, final Collection results) {
        for (int i = 0; i < files.length; i++) {
            assertTrue(results.contains(files[i]), prefix + "[" + i + "] " + files[i]);
        }
    }

    /**
     * Extract the directories.
     */
    private List directoriesOnly(final Collection<File> results) {
        final List list = new ArrayList(results.size());
        for (final File file : results) {
            if (file.isDirectory()) {
                list.add(file);
            }
        }
        return list;
    }

    /**
     * Extract the files.
     */
    private List filesOnly(final Collection<File> results) {
        final List list = new ArrayList(results.size());
        for (final File file : results) {
            if (file.isFile()) {
                list.add(file);
            }
        }
        return list;
    }

    /**
     * Test Cancel
     * @throws IOException
     */
    @Test
    public void testCancel() throws IOException {
        String cancelName = null;

        // Cancel on a file
        try {
            cancelName = "DirectoryWalker.java";
            new TestCancelWalker(cancelName, false).find(javaDir);
            fail("CancelException not thrown for '" + cancelName + "'");
        } catch (final DirectoryWalker.CancelException cancel) {
            assertEquals(cancelName, cancel.getFile().getName(), "File:  " + cancelName);
            assertEquals(5, cancel.getDepth(), "Depth: " + cancelName);
        }

        // Cancel on a directory
        try {
            cancelName = "commons";
            new TestCancelWalker(cancelName, false).find(javaDir);
            fail("CancelException not thrown for '" + cancelName + "'");
        } catch (final DirectoryWalker.CancelException cancel) {
            assertEquals(cancelName, cancel.getFile().getName(), "File:  " + cancelName);
            assertEquals(3, cancel.getDepth(), "Depth: " + cancelName);
        }

        // Suppress CancelException (use same file name as preceding test)
        final List results = new TestCancelWalker(cancelName, true).find(javaDir);
        final File lastFile = (File) results.get(results.size() - 1);
        assertEquals(cancelName, lastFile.getName(), "Suppress:  " + cancelName);
    }

    /**
     * Test Filtering
     */
    @Test
    public void testFilter() {
        final List<File> results = new TestFileFinder(dirsAndFilesFilter, -1).find(javaDir);
        assertEquals(1 + dirs.length + ioFiles.length + outputFiles.length, results.size(), "Result Size");
        assertTrue(results.contains(javaDir), "Start Dir");
        checkContainsFiles("Dir", dirs, results);
        checkContainsFiles("IO File", ioFiles, results);
        checkContainsFiles("Output File", outputFiles, results);
    }

    /**
     * Test Filtering and limit to depth 0
     */
    @Test
    public void testFilterAndLimitA() {
        final List<File> results = new TestFileFinder(NOT_SVN, 0).find(javaDir);
        assertEquals(1, results.size(), "[A] Result Size");
        assertTrue(results.contains(javaDir), "[A] Start Dir");
    }

    /**
     * Test Filtering and limit to depth 1
     */
    @Test
    public void testFilterAndLimitB() {
        final List<File> results = new TestFileFinder(NOT_SVN, 1).find(javaDir);
        assertEquals(2, results.size(), "[B] Result Size");
        assertTrue(results.contains(javaDir), "[B] Start Dir");
        assertTrue(results.contains(orgDir), "[B] Org Dir");
    }

    // ------------ Convenience Test Methods ------------------------------------

    /**
     * Test Filtering and limit to depth 3
     */
    @Test
    public void testFilterAndLimitC() {
        final List<File> results = new TestFileFinder(NOT_SVN, 3).find(javaDir);
        assertEquals(4, results.size(), "[C] Result Size");
        assertTrue(results.contains(javaDir), "[C] Start Dir");
        assertTrue(results.contains(orgDir), "[C] Org Dir");
        assertTrue(results.contains(apacheDir), "[C] Apache Dir");
        assertTrue(results.contains(commonsDir), "[C] Commons Dir");
    }

    /**
     * Test Filtering and limit to depth 5
     */
    @Test
    public void testFilterAndLimitD() {
        final List<File> results = new TestFileFinder(dirsAndFilesFilter, 5).find(javaDir);
        assertEquals(1 + dirs.length + ioFiles.length, results.size(), "[D] Result Size");
        assertTrue(results.contains(javaDir), "[D] Start Dir");
        checkContainsFiles("[D] Dir", dirs, results);
        checkContainsFiles("[D] File", ioFiles, results);
    }

    /**
     * Test separate dir and file filters
     */
    @Test
    public void testFilterDirAndFile1() {
        final List<File> results = new TestFileFinder(dirsFilter, ioFilesFilter, -1).find(javaDir);
        assertEquals(1 + dirs.length + ioFiles.length, results.size(), "[DirAndFile1] Result Size");
        assertTrue(results.contains(javaDir), "[DirAndFile1] Start Dir");
        checkContainsFiles("[DirAndFile1] Dir", dirs, results);
        checkContainsFiles("[DirAndFile1] File", ioFiles, results);
    }

    /**
     * Test separate dir and file filters
     */
    @Test
    public void testFilterDirAndFile2() {
        final List<File> results = new TestFileFinder(null, null, -1).find(javaDir);
        assertTrue(results.size() > 1 + dirs.length + ioFiles.length, "[DirAndFile2] Result Size");
        assertTrue(results.contains(javaDir), "[DirAndFile2] Start Dir");
        checkContainsFiles("[DirAndFile2] Dir", dirs, results);
        checkContainsFiles("[DirAndFile2] File", ioFiles, results);
    }

    /**
     * Test separate dir and file filters
     */
    @Test
    public void testFilterDirAndFile3() {
        final List<File> results = new TestFileFinder(dirsFilter, null, -1).find(javaDir);
        final List resultDirs = directoriesOnly(results);
        assertEquals(1 + dirs.length, resultDirs.size(), "[DirAndFile3] Result Size");
        assertTrue(results.contains(javaDir), "[DirAndFile3] Start Dir");
        checkContainsFiles("[DirAndFile3] Dir", dirs, resultDirs);
    }

    /**
     * Test separate dir and file filters
     */
    @Test
    public void testFilterDirAndFile4() {
        final List<File> results = new TestFileFinder(null, ioFilesFilter, -1).find(javaDir);
        final List resultFiles = filesOnly(results);
        assertEquals(ioFiles.length, resultFiles.size(), "[DirAndFile4] Result Size");
        assertTrue(results.contains(javaDir), "[DirAndFile4] Start Dir");
        checkContainsFiles("[DirAndFile4] File", ioFiles, resultFiles);
    }

    /**
     * test an invalid start directory
     */
    @Test
    public void testHandleStartDirectoryFalse() {

        final List<File> results = new TestFalseFileFinder(null, -1).find(current);
        assertEquals(0, results.size(), "Result Size");

    }

    /**
     * Test Limiting to current directory
     */
    @Test
    public void testLimitToCurrent() {
        final List<File> results = new TestFileFinder(null, 0).find(current);
        assertEquals(1, results.size(), "Result Size");
        assertTrue(results.contains(FileUtils.current()), "Current Dir");
    }

    /**
     * Test an invalid start directory
     */
    @Test
    public void testMissingStartDirectory() {

        // TODO is this what we want with invalid directory?
        final File invalidDir = new File("invalid-dir");
        final List<File> results = new TestFileFinder(null, -1).find(invalidDir);
        assertEquals(1, results.size(), "Result Size");
        assertTrue(results.contains(invalidDir), "Current Dir");

        assertThrows(NullPointerException.class, () -> new TestFileFinder(null, -1).find(null));
    }

    /**
     * Test Cancel
     * @throws IOException
     */
    @Test
    public void testMultiThreadCancel() throws IOException {
        String cancelName = "DirectoryWalker.java";
        TestMultiThreadCancelWalker walker = new TestMultiThreadCancelWalker(cancelName, false);
        // Cancel on a file
        try {
            walker.find(javaDir);
            fail("CancelException not thrown for '" + cancelName + "'");
        } catch (final DirectoryWalker.CancelException cancel) {
            final File last = (File) walker.results.get(walker.results.size() - 1);
            assertEquals(cancelName, last.getName());
            assertEquals(5, cancel.getDepth(), "Depth: " + cancelName);
        }

        // Cancel on a directory
        try {
            cancelName = "commons";
            walker = new TestMultiThreadCancelWalker(cancelName, false);
            walker.find(javaDir);
            fail("CancelException not thrown for '" + cancelName + "'");
        } catch (final DirectoryWalker.CancelException cancel) {
            assertEquals(cancelName, cancel.getFile().getName(), "File:  " + cancelName);
            assertEquals(3, cancel.getDepth(), "Depth: " + cancelName);
        }

        // Suppress CancelException (use same file name as preceding test)
        walker = new TestMultiThreadCancelWalker(cancelName, true);
        final List results = walker.find(javaDir);
        final File lastFile = (File) results.get(results.size() - 1);
        assertEquals(cancelName, lastFile.getName(), "Suppress:  " + cancelName);

    }

}