001/* 002 * SonarQube, open source software quality management tool. 003 * Copyright (C) 2008-2014 SonarSource 004 * mailto:contact AT sonarsource DOT com 005 * 006 * SonarQube is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * SonarQube is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public License 017 * along with this program; if not, write to the Free Software Foundation, 018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 019 */ 020package org.sonar.api.utils.internal; 021 022import org.apache.commons.io.FileUtils; 023import org.sonar.api.utils.TempFolder; 024 025import javax.annotation.Nullable; 026 027import java.io.File; 028import java.io.IOException; 029import java.nio.file.Files; 030import java.nio.file.Path; 031 032public class DefaultTempFolder implements TempFolder { 033 034 private final File tempDir; 035 private final boolean deleteOnExit; 036 037 public DefaultTempFolder(File tempDir) { 038 this(tempDir, false); 039 } 040 041 public DefaultTempFolder(File tempDir, boolean deleteOnExit) { 042 this.tempDir = tempDir; 043 this.deleteOnExit = deleteOnExit; 044 } 045 046 @Override 047 public File newDir() { 048 return createTempDir(tempDir.toPath()).toFile(); 049 } 050 051 private static Path createTempDir(Path baseDir) { 052 try { 053 return Files.createTempDirectory(baseDir, null); 054 } catch (IOException e) { 055 throw new IllegalStateException("Failed to create temp directory", e); 056 } 057 } 058 059 @Override 060 public File newDir(String name) { 061 File dir = new File(tempDir, name); 062 try { 063 FileUtils.forceMkdir(dir); 064 } catch (IOException e) { 065 throw new IllegalStateException("Failed to create temp directory - " + dir, e); 066 } 067 return dir; 068 } 069 070 @Override 071 public File newFile() { 072 return newFile(null, null); 073 } 074 075 @Override 076 public File newFile(@Nullable String prefix, @Nullable String suffix) { 077 return createTempFile(tempDir.toPath(), prefix, suffix).toFile(); 078 } 079 080 private static Path createTempFile(Path baseDir, String prefix, String suffix) { 081 try { 082 return Files.createTempFile(baseDir, prefix, suffix); 083 } catch (IOException e) { 084 throw new IllegalStateException("Failed to create temp file", e); 085 } 086 } 087 088 public void clean() { 089 FileUtils.deleteQuietly(tempDir); 090 } 091 092 public void stop() { 093 if (deleteOnExit) { 094 clean(); 095 } 096 } 097 098}