View Javadoc
1   /*
2    * Copyright 2020 The Netty Project
3    *
4    * The Netty Project 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  package io.netty.handler.codec.http.multipart;
17  
18  import java.io.File;
19  import java.util.Collections;
20  import java.util.Set;
21  import java.util.concurrent.ConcurrentHashMap;
22  
23  /**
24   * DeleteFileOnExitHook.
25   */
26  final class DeleteFileOnExitHook {
27      private static final Set<String> FILES = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
28  
29      private DeleteFileOnExitHook() {
30      }
31  
32      static {
33          // DeleteOnExitHook must be the last shutdown hook to be invoked.
34          // Application shutdown hooks may add the first file to the
35          // delete on exit list and cause the DeleteOnExitHook to be
36          // registered during shutdown in progress.
37          Runtime.getRuntime().addShutdownHook(new Thread() {
38  
39              @Override
40              public void run() {
41                  runHook();
42              }
43          });
44      }
45  
46      /**
47       * Remove from the pool to reduce space footprint.
48       *
49       * @param file tmp file path
50       */
51      public static void remove(String file) {
52          FILES.remove(file);
53      }
54  
55      /**
56       * Add to the hook and clean up when the program exits.
57       *
58       * @param file tmp file path
59       */
60      public static void add(String file) {
61          FILES.add(file);
62      }
63  
64      /**
65       * Check in the hook files.
66       *
67       * @param file target file
68       * @return true or false
69       */
70      public static boolean checkFileExist(String file) {
71          return FILES.contains(file);
72      }
73  
74      /**
75       * Clean up all the files.
76       */
77      static void runHook() {
78          for (String filename : FILES) {
79              new File(filename).delete();
80          }
81      }
82  }