1 /*******************************************************************************
2  * Copyright (c) 2009, 2013 IBM Corporation and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     IBM Corporation - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.pde.api.tools.internal.util;
15 
16 import java.io.File;
17 import java.util.HashSet;
18 
19 /**
20  * Manager to handle temporary files that have been created. Used as a fall-back
21  * to ensure we clean up after ourselves
22  *
23  * @since 1.0.1
24  */
25 public final class FileManager {
26 
27 	private static FileManager fInstance = null;
28 
29 	/**
30 	 * The set of recorded file paths
31 	 */
32 	private static HashSet<String> fFilePaths = null;
33 
34 	/**
35 	 * Constructor private - no instantiation
36 	 */
FileManager()37 	private FileManager() {
38 	}
39 
40 	/**
41 	 * Returns the singleton instance of the manager
42 	 *
43 	 * @return the manager instance
44 	 */
getManager()45 	public synchronized static FileManager getManager() {
46 		if (fInstance == null) {
47 			fInstance = new FileManager();
48 		}
49 		return fInstance;
50 	}
51 
52 	/**
53 	 * Records a file root path to be deleted on the next call to
54 	 * {@link #deleteFiles()}.
55 	 *
56 	 * @param absolutepath the absolute path in the local file system of the
57 	 *            file to delete
58 	 */
recordTempFileRoot(String absolutepath)59 	public void recordTempFileRoot(String absolutepath) {
60 		if (absolutepath != null) {
61 			if (fFilePaths == null) {
62 				fFilePaths = new HashSet<>(10);
63 			}
64 			synchronized (fFilePaths) {
65 				fFilePaths.add(absolutepath);
66 			}
67 		}
68 	}
69 
70 	/**
71 	 * Deletes all of the recorded file roots from the local filesystem (if
72 	 * still existing) and returns the success of the entire delete operation.
73 	 *
74 	 * @return true if all recorded files were deleted, false otherwise
75 	 */
deleteFiles()76 	public boolean deleteFiles() {
77 		boolean success = true;
78 		if (fFilePaths != null) {
79 			synchronized (fFilePaths) {
80 				try {
81 					File file = null;
82 					for (String filename : fFilePaths) {
83 						file = new File(filename);
84 						success &= Util.delete(file);
85 					}
86 				} finally {
87 					fFilePaths.clear();
88 				}
89 			}
90 		}
91 		return success;
92 	}
93 }
94