View Javadoc
1   /*
2    * Copyright 2024 Hochschule Luzern Informatik.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * Codevorlage zu CountedCompleter für eine Dateisuche.
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       * Erzeugt eine File-Such-Aufgabe.
36       *
37       * @param regex Ausdruck der den Filenamen enthält.
38       * @param dir   Verzeichnis in dem das File gesucht wird.
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  }