package org.apache.poi.util;
import java.io.File;
-import java.util.Random;
+import java.io.IOException;
/**
- * Interface for creating temporary files. Collects them all into one directory.
- *
- * @author Glen Stampoultzis
+ * Interface for creating temporary files. Collects them all into one directory by default.
*/
public final class TempFile {
- private static File dir;
- private static final Random rnd = new Random();
-
+
+ /** The strategy used by {@link #createTempFile(String, String)} to create the temporary files. */
+ private static TempFileCreationStrategy strategy = new DefaultTempFileCreationStrategy();
+
/**
- * Creates a temporary file. Files are collected into one directory and by default are
- * deleted on exit from the VM. Files can be kept by defining the system property
- * <code>poi.keep.tmp.files</code>.
+ * Configures the strategy used by {@link #createTempFile(String, String)} to create the temporary files.
+ *
+ * @param strategy The new strategy to be used to create the temporary files.
+ *
+ * @throws IllegalArgumentException When the given strategy is <code>null</code>.
+ */
+ public static void setTempFileCreationStrategy(TempFileCreationStrategy strategy) {
+ if (strategy == null) {
+ throw new IllegalArgumentException("strategy == null");
+ }
+ TempFile.strategy = strategy;
+ }
+
+ /**
+ * Creates a new and empty temporary file. By default, files are collected into one directory and are
+ * deleted on exit from the VM, although they can be kept by defining the system property
+ * <code>poi.keep.tmp.files</code> (see {@link DefaultTempFileCreationStrategy}).
* <p>
* Don't forget to close all files or it might not be possible to delete them.
+ *
+ * @param prefix The prefix to be used to generate the name of the temporary file.
+ * @param suffix The suffix to be used to generate the name of the temporary file.
+ *
+ * @return The path to the newly created and empty temporary file.
+ *
+ * @throws IOException If no temporary file could be created.
*/
- public static File createTempFile(String prefix, String suffix) {
- // Identify and create our temp dir, if needed
- if (dir == null)
- {
- dir = new File(System.getProperty("java.io.tmpdir"), "poifiles");
- dir.mkdir();
- if (System.getProperty("poi.keep.tmp.files") == null)
- dir.deleteOnExit();
+ public static File createTempFile(String prefix, String suffix) throws IOException {
+ return strategy.createTempFile(prefix, suffix);
+ }
+
+ /**
+ * Default implementation of the {@link TempFileCreationStrategy} used by {@link TempFile}:
+ * Files are collected into one directory and by default are deleted on exit from the VM.
+ * Files can be kept by defining the system property <code>poi.keep.tmp.files</code>.
+ */
+ public static class DefaultTempFileCreationStrategy implements TempFileCreationStrategy {
+
+ /** The directory where the temporary files will be created (<code>null</code> to use the default directory). */
+ private File dir;
+
+ /**
+ * Creates the strategy so that it creates the temporary files in the default directory.
+ *
+ * @see File#createTempFile(String, String)
+ */
+ public DefaultTempFileCreationStrategy() {
+ this(null);
}
-
- // Generate a unique new filename
- File newFile = new File(dir, prefix + rnd.nextInt() + suffix);
- if (newFile.exists())
- {
- // That name is already taken, try another
- newFile = createTempFile(prefix, suffix);
+
+ /**
+ * Creates the strategy allowing to set the
+ *
+ * @param dir The directory where the temporary files will be created (<code>null</code> to use the default directory).
+ *
+ * @see File#createTempFile(String, String, File)
+ */
+ public DefaultTempFileCreationStrategy(File dir) {
+ this.dir = dir;
}
+
+ @Override
+ public File createTempFile(String prefix, String suffix) throws IOException {
+ // Identify and create our temp dir, if needed
+ if (dir == null)
+ {
+ dir = new File(System.getProperty("java.io.tmpdir"), "poifiles");
+ dir.mkdir();
+ if (System.getProperty("poi.keep.tmp.files") == null)
+ dir.deleteOnExit();
+ }
- // Set the delete on exit flag, unless explicitly disabled
- if (System.getProperty("poi.keep.tmp.files") == null)
- newFile.deleteOnExit();
+ // Generate a unique new filename
+ File newFile = File.createTempFile(prefix, suffix, dir);
- // All done
- return newFile;
+ // Set the delete on exit flag, unless explicitly disabled
+ if (System.getProperty("poi.keep.tmp.files") == null)
+ newFile.deleteOnExit();
+
+ // All done
+ return newFile;
+ }
+
}
}
--- /dev/null
+/* ====================================================================
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+==================================================================== */
+
+package org.apache.poi.util;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Interface used by the {@link TempFile} utility class to create temporary files.
+ */
+public interface TempFileCreationStrategy {
+ /**
+ * Creates a new and empty temporary file.
+ *
+ * @param prefix The prefix to be used to generate the name of the temporary file.
+ * @param suffix The suffix to be used to generate the name of the temporary file.
+ *
+ * @return The path to the newly created and empty temporary file.
+ *
+ * @throws IOException If no temporary file could be created.
+ */
+ public File createTempFile(String prefix, String suffix) throws IOException;
+}
import org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
+import org.apache.poi.util.TempFile;
/**
* Physical zip package.
if (targetFile.exists()) {
// Case of a package previously open
- File tempFile = File.createTempFile(
+ File tempFile = TempFile.createTempFile(
generateTempFileName(FileHelper
.getDirectory(targetFile)), ".tmp");
/**
* Provides handy methods to work with OOXML packages
- *
- * @author Yegor Kozlov
*/
public final class PackageHelper {
return OPCPackage.open(path);
}
- /**
- * Creates an empty file in the default temporary-file directory,
- */
- public static File createTempFile() {
- File file = TempFile.createTempFile("poi-ooxml-", ".tmp");
- //there is no way to pass an existing file to Package.create(file),
- //delete first, the file will be re-created in Packe.create(file)
- file.delete();
- return file;
-
- }
-
/**
* Recursively copy package parts to the destination package
*/
import java.util.zip.GZIPInputStream;\r
import java.util.zip.GZIPOutputStream;\r
\r
+import org.apache.poi.util.TempFile;\r
import org.apache.poi.xssf.model.SharedStringsTable;\r
\r
/**\r
* @return temp file to write sheet data\r
*/\r
@Override\r
- public File createTempFile()throws IOException {\r
- return File.createTempFile("poi-sxssf-sheet-xml", ".gz");\r
+ public File createTempFile() throws IOException {\r
+ return TempFile.createTempFile("poi-sxssf-sheet-xml", ".gz");\r
}\r
\r
/**\r
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
}
//Save the template
- File tmplFile = File.createTempFile("poi-sxssf-template", ".xlsx");
+ File tmplFile = TempFile.createTempFile("poi-sxssf-template", ".xlsx");
try
{
FileOutputStream os = new FileOutputStream(tmplFile);
import org.apache.poi.ss.usermodel.CellStyle;\r
import org.apache.poi.ss.usermodel.FormulaError;\r
import org.apache.poi.ss.util.CellReference;\r
+import org.apache.poi.util.TempFile;\r
import org.apache.poi.xssf.model.SharedStringsTable;\r
import org.apache.poi.xssf.usermodel.XSSFRichTextString;\r
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;\r
* \r
* @return temp file to write sheet data\r
*/\r
- public File createTempFile()throws IOException {\r
- return File.createTempFile("poi-sxssf-sheet", ".xml");\r
+ public File createTempFile() throws IOException {\r
+ return TempFile.createTempFile("poi-sxssf-sheet", ".xml");\r
}\r
\r
/**\r
import java.io.File;
import java.io.InputStream;
+import java.io.IOException;
/**
* Centralises logic for finding/opening sample files for ooxml4j unit tests
- *
- * @author jmicich
*/
public final class OpenXML4JTestDataSamples {
private static final POIDataSamples _samples = POIDataSamples.getOpenXML4JInstance();
return _samples.getFile(sampleFileName);
}
- public static File getOutputFile(String outputFileName) {
+ public static File getOutputFile(String outputFileName) throws IOException {
String suffix = outputFileName.substring(outputFileName.lastIndexOf('.'));
return TempFile.createTempFile(outputFileName, suffix);
}
* write changes to it.
*/
public void testOpenFileThenOverwrite() throws Exception {
- File tempFile = File.createTempFile("poiTesting","tmp");
+ File tempFile = TempFile.createTempFile("poiTesting","tmp");
File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
FileHelper.copyFile(origFile, tempFile);
* to another file, then delete both
*/
public void testOpenFileThenSaveDelete() throws Exception {
- File tempFile = File.createTempFile("poiTesting","tmp");
- File tempFile2 = File.createTempFile("poiTesting","tmp");
+ File tempFile = TempFile.createTempFile("poiTesting","tmp");
+ File tempFile2 = TempFile.createTempFile("poiTesting","tmp");
File origFile = OpenXML4JTestDataSamples.getSampleFile("TestPackageCommon.docx");
FileHelper.copyFile(origFile, tempFile);
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
+import org.apache.poi.util.TempFile;
import org.junit.Test;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
}
// save the worksheet as-is using SXSSF
- File outputFile = File.createTempFile("poi-56274", ".xlsx");
+ File outputFile = TempFile.createTempFile("poi-56274", ".xlsx");
SXSSFWorkbook outputWorkbook = new org.apache.poi.xssf.streaming.SXSSFWorkbook(inputWorkbook);
outputWorkbook.write(new FileOutputStream(outputFile));
import org.apache.poi.POIDataSamples;\r
import org.apache.poi.hslf.model.Slide;\r
import org.apache.poi.hslf.model.TextPainter;\r
+import org.apache.poi.util.TempFile;\r
import org.junit.Ignore;\r
import org.junit.Test;\r
\r
\r
// allow to find out what the actual difference is in CI where this fails currently\r
if(!Arrays.equals(expectedData, actualData)) {\r
- ImageIO.write(imgActual, "PNG", File.createTempFile("TestFontRendering", ".png"));\r
+ ImageIO.write(imgActual, "PNG", TempFile.createTempFile("TestFontRendering", ".png"));\r
}\r
assertTrue("Expected to have matching raster-arrays, but found differences, size " + expectedData.length + " and " + actualData.length, \r
Arrays.equals(expectedData, actualData));\r
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.usermodel.BaseTestNamedRange;
import org.apache.poi.ss.util.AreaReference;
+import org.apache.poi.util.TempFile;
/**
* Tests various functionality having to do with {@link org.apache.poi.ss.usermodel.Name}.
- *
- * @author Andrew C. Oliver (acoliver at apache dot org)
- * @author ROMANL
- * @author Danny Mui (danny at muibros.com)
- * @author Amol S. Deshmukh < amol at ap ache dot org >
*/
public final class TestHSSFName extends BaseTestNamedRange {
// In case you fancy checking in excel, to ensure it
// won't complain about the file now
try {
- File tempFile = File.createTempFile("POI-45126-", ".xls");
+ File tempFile = TempFile.createTempFile("POI-45126-", ".xls");
FileOutputStream fout = new FileOutputStream(tempFile);
nwb.write(fout);
fout.close();
package org.apache.poi.ss.formula.function;
+import org.apache.poi.util.TempFile;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
* the file 'functionMetadata.txt'. There are more than 300 built-in functions in Excel and the
* intention of this class is to make it easier to maintain the metadata, by extracting it from
* a reliable source.
- *
- * @author Josh Micich
*/
public final class ExcelFileFormatDocFunctionExtractor {
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
System.out.println("downloading " + url.toExternalForm());
- result = File.createTempFile("excelfileformat", ".odt");
+ result = TempFile.createTempFile("excelfileformat", ".odt");
OutputStream os = new FileOutputStream(result);
while(true) {
int bytesRead = is.read(buf);
package org.apache.poi.ss.formula.ptg;
+import org.apache.poi.util.TempFile;
+
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.CellValue;
/**
* Tests for functions from external workbooks (e.g. YEARFRAC).
- *
- *
- * @author Josh Micich
*/
public final class TestExternalFunctionFormulas extends TestCase {
if (false) {
// In case you fancy checking in excel
try {
- File tempFile = File.createTempFile("testExtFunc", ".xls");
+ File tempFile = TempFile.createTempFile("testExtFunc", ".xls");
FileOutputStream fout = new FileOutputStream(tempFile);
wb.write(fout);
fout.close();