GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

io.github.glytching.junit.extension.folder.TemporaryFolder   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 110
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 110
rs 10
eloc 45
wmc 13

9 Methods

Rating   Name   Duplication   Size   Complexity  
A TemporaryFolder() 0 8 2
$SimpleFileVisitor$.postVisitDirectory(Path,IOException) 0 4 ?
A createDirectory(String) 0 7 2
A createFile(String) 0 3 1
$SimpleFileVisitor$.visitFile(Path,BasicFileAttributes) 0 4 ?
A getRoot() 0 2 1
A close() 0 3 1
B destroy() 0 28 6
$SimpleFileVisitor$.delete(Path) 0 4 ?
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 *
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
package io.github.glytching.junit.extension.folder;
18
19
import org.junit.jupiter.api.extension.ExtensionContext.Store.CloseableResource;
20
21
import java.io.File;
22
import java.io.IOException;
23
import java.nio.file.*;
24
import java.nio.file.attribute.BasicFileAttributes;
25
26
import static java.nio.file.FileVisitResult.CONTINUE;
27
28
/**
29
 * Encapsulates the {@link #rootFolder} within which any files or directories will be created along
30
 * with the operations which a tester may wish to invoke ({@link #createFile(String)}, {@link
31
 * #createDirectory(String)}) and post test invocations which the associated extension will invoke.
32
 */
33
@SuppressWarnings({"ResultOfMethodCallIgnored", "nls"})
34
public class TemporaryFolder implements CloseableResource {
35
  private static final String FILE_PREFIX = "junit";
36
  private static final String FILE_SUFFIX = ".tmp";
0 ignored issues
show
Unused Code introduced by
Consider removing the unused private field FILE_SUFFIX.
Loading history...
37
38
  /**
39
   * The root folder within which any files or directories will be created, on {@link #destroy()}
40
   * this folder and all of its contents will be silently deleted.
41
   */
42
  private final File rootFolder;
43
44
  /**
45
   * Package protected since a {@link TemporaryFolder}'s lifecycle is expected to be controlled by
46
   * its associated extension.
47
   */
48
  TemporaryFolder() {
49
    try {
50
      // do not use Files.createTempFile to create a directory
51
      // see https://rules.sonarsource.com/java/RSPEC-2976
52
      Path tempPath = Files.createTempDirectory(FILE_PREFIX);
53
      rootFolder = tempPath.toFile();
54
    } catch (IOException ex) {
55
      throw new TemporaryFolderException("Failed to prepare root folder!", ex);
56
    }
57
  }
58
59
  @Override
60
  public void close() throws Throwable {
61
    destroy();
62
  }
63
64
  /**
65
   * Returns the root folder. Exposing this offers some back compatability with JUnit4's {@code
66
   * TemporaryFolder} so test cases which are used to invoking {@code getRoot()} on a JUnit4 rule
67
   * can adopt the same approach with this {@code TemporaryFolder}. In addition, this may be useful
68
   * where you want to use the root folder itself without creating files or directories within it.
69
   *
70
   * <p><b>Note:</b> the extension is responsible for creating/managing/destroying the root folder
71
   * so don't bother trying to clean it up yourself and don't expect that anything you do to it will
72
   * survive post-test-cleanup.
73
   *
74
   * @see <a href="https://github.com/glytching/junit-extensions/issues/8">Issue 8</a>
75
   * @return the root folder
76
   */
77
  public File getRoot() {
78
    return rootFolder;
79
  }
80
81
  /**
82
   * Create a file within the temporary folder root.
83
   *
84
   * @param fileName the name of the file to be created
85
   * @return the newly created file instance
86
   * @throws IOException in case the file creation call fails
87
   */
88
  public File createFile(String fileName) throws IOException {
89
    Path path = Paths.get(rootFolder.getPath(), fileName);
90
    return Files.createFile(path).toFile();
91
  }
92
93
  /**
94
   * Create a directory within the temporary folder root.
95
   *
96
   * @param directoryName the name of the directory to be created
97
   * @return the directory instance
98
   */
99
  public File createDirectory(String directoryName) {
100
    Path path = Paths.get(rootFolder.getPath(), directoryName);
101
    try {
102
      return Files.createDirectory(path).toFile();
103
    } catch (IOException ex) {
104
      throw new TemporaryFolderException(
105
          String.format("Failed to create directory: '%s'", path.toString()), ex);
106
    }
107
  }
108
109
  /**
110
   * Deletes the {@link #rootFolder} and all of its contents. This is package protected because a
111
   * {@link TemporaryFolder}'s lifecycle is expected to be controlled by its associated extension.
112
   *
113
   * <p><b>Note</b>: any exception encountered during deletion will be swallowed.
114
   */
115
  void destroy() throws IOException {
116
    if (rootFolder.exists()) {
117
      // walk the contents deleting each
118
      Files.walkFileTree(
119
          rootFolder.toPath(),
120
          new SimpleFileVisitor<Path>() {
121
            @Override
122
            public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
123
                throws IOException {
124
              return delete(file);
125
            }
126
127
            @Override
128
            public FileVisitResult postVisitDirectory(Path directory, IOException exception)
129
                throws IOException {
130
              return delete(directory);
131
            }
132
133
            @SuppressWarnings("SameReturnValue")
134
            private FileVisitResult delete(Path file) throws IOException {
135
              Files.delete(file);
136
              return CONTINUE;
137
            }
138
          });
139
140
      if (rootFolder.exists()) {
141
        // delete the parent, if it still exists
142
        Files.delete(rootFolder.toPath());
143
      }
144
    }
145
  }
146
}
147