1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package ch.hslu.exercises.sw11.ex4.findfile;
17
18 import java.io.File;
19 import java.util.Arrays;
20 import java.util.Collections;
21 import java.util.concurrent.CountedCompleter;
22 import java.util.concurrent.atomic.AtomicReference;
23
24
25
26
27 public final class FindFileTask extends CountedCompleter<String> {
28
29 private final String regex;
30 private final File dir;
31 private final AtomicReference<String> result;
32 private static final String INITIAL_RESULT_VALUE = null;
33
34
35
36
37
38
39
40 public FindFileTask(String regex, File dir) {
41 this(null, regex, dir, new AtomicReference<>(INITIAL_RESULT_VALUE));
42 }
43
44 private FindFileTask(final CountedCompleter<?> parent, final String regex, final File dir,
45 final AtomicReference<String> result) {
46 super(parent);
47 this.regex = regex;
48 this.dir = dir;
49 this.result = result;
50 }
51
52 @Override
53 public void compute() {
54 final File[] list = dir.listFiles();
55 if (list != null) {
56 for (File file : list) {
57 if (file.isDirectory()) {
58 this.addToPendingCount(1);
59 new FindFileTask(this, regex, file, result).fork();
60 } else if (regex.equalsIgnoreCase(file.getName())
61 && result.compareAndSet(INITIAL_RESULT_VALUE, file.getParent())) {
62 this.quietlyCompleteRoot();
63 break;
64 }
65 }
66 }
67 tryComplete();
68 }
69
70 @Override
71 public String getRawResult() {
72 if (result != null) {
73 return result.get();
74 }
75 return null;
76 }
77 }