7cd5228ccef594fe3ec15748c386ca5e67aa228d
[policy/apex-pdp.git] / model / utilities / src / main / java / org / onap / policy / apex / model / utilities / DirectoryUtils.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * 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  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.model.utilities;
22
23 import java.io.File;
24
25 import org.slf4j.ext.XLogger;
26 import org.slf4j.ext.XLoggerFactory;
27
28 /**
29  * This is common utility class with static methods for handling directories. It is an abstract class to prevent any
30  * direct instantiation and private constructor to prevent extending this class.
31  *
32  * @author Liam Fallon (liam.fallon@ericsson.com)
33  */
34 public abstract class DirectoryUtils {
35     // Get a reference to the logger
36     private static final XLogger LOGGER = XLoggerFactory.getXLogger(DirectoryUtils.class);
37
38     /**
39      * Private constructor used to prevent sub class instantiation.
40      */
41     private DirectoryUtils() {
42     }
43
44     /**
45      * Method to get an empty temporary directory in the system temporary directory on the local machine that will be
46      * deleted on (normal) shutdown.
47      *
48      * @param nameprefix The prefix of the filename. System.nanoTime() will be appended to the pattern to create a
49      *        unique file pattern
50      * @return The temporary directory
51      */
52     public static File getLocalTempDirectory(final String nameprefix) {
53         try {
54             // Get the name of the temporary directory
55             final String tempDirName = System.getProperty("java.io.tmpdir") + "/" + nameprefix + System.nanoTime();
56             final File tempDir = new File(tempDirName);
57
58             // Delete the directory if it already exists
59             if (tempDir.exists()) {
60                 return null;
61             }
62
63             // Make the directory
64             tempDir.mkdirs();
65
66             // Add a shutdown hook that deletes the directory contents when the JVM closes
67             Runtime.getRuntime().addShutdownHook(new DirectoryDeleteShutdownHook(tempDir));
68
69             LOGGER.trace("creating temp directory\"{}\" : ", tempDir.getAbsolutePath());
70             return tempDir;
71         } catch (final Exception e) {
72             LOGGER.debug("error creating temp directory\"{}\" : " + e.getMessage(), e);
73             return null;
74         }
75     }
76
77     /**
78      * Method to recursively delete all the files in a directory.
79      *
80      * @param tempDir the directory to empty
81      * @return true if the operation succeeds, false otherwise
82      */
83     public static boolean emptyDirectory(final File tempDir) {
84         // Sanity check
85         if (!tempDir.exists() || !tempDir.isDirectory()) {
86             return false;
87         }
88
89         // Walk the directory structure deleting files as we go
90         final File[] files = tempDir.listFiles();
91         if (files != null) {
92             for (final File directoryFile : files) {
93                 // Check if this is a directory itself
94                 if (directoryFile.isDirectory()) {
95                     // Recurse into the sub directory and empty it
96                     emptyDirectory(directoryFile);
97                 }
98
99                 // Delete the directory entry
100                 directoryFile.delete();
101             }
102         }
103
104         return true;
105     }
106 }