1   /*
2    * Copyright 2020 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package com.linecorp.centraldogma.testing.internal;
18  
19  import java.io.File;
20  import java.io.IOException;
21  import java.nio.file.Files;
22  import java.nio.file.Path;
23  import java.util.Comparator;
24  import java.util.stream.Stream;
25  
26  import javax.annotation.Nullable;
27  
28  /**
29   * A helper class to handle temporary folders in JUnit {@code Extension}s.
30   */
31  public class TemporaryFolder {
32  
33      @Nullable
34      private Path root;
35  
36      public void create() throws IOException {
37          root = Files.createTempDirectory("centraldogma");
38      }
39  
40      public boolean exists() {
41          return root != null;
42      }
43  
44      public Path getRoot() {
45          if (root == null) {
46              throw new IllegalStateException("The temporary folder has not been created yet");
47          }
48  
49          return root;
50      }
51  
52      public Path newFolder() throws IOException {
53          return Files.createTempDirectory(getRoot(), "");
54      }
55  
56      public Path newFile() throws IOException {
57          return Files.createTempFile(getRoot(), "", "");
58      }
59  
60      public void delete() throws IOException {
61          if (root == null) {
62              return;
63          }
64  
65          try (Stream<Path> walk = Files.walk(root)) {
66              walk.sorted(Comparator.reverseOrder())
67                  .map(Path::toFile)
68                  .forEach(File::delete);
69          }
70  
71          root = null;
72      }
73  }