[bug-69714] add thread local support for overriding TempFile strategy

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1926466 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
PJ Fanning 2025-06-16 11:01:40 +00:00
parent 9c08d29fcb
commit 6605569862
2 changed files with 37 additions and 6 deletions

View File

@ -59,14 +59,9 @@ public final class TempFile {
* 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>.
* @since POI 5.4.2
*/
public static void setThreadLocalTempFileCreationStrategy(TempFileCreationStrategy strategy) {
if (strategy == null) {
throw new IllegalArgumentException("strategy == null");
}
threadLocalStrategy.set(strategy);
}
@ -95,6 +90,6 @@ public final class TempFile {
private static TempFileCreationStrategy getStrategy() {
TempFileCreationStrategy s = threadLocalStrategy.get();
return s == null ? strategy: s;
return s == null ? strategy : s;
}
}

View File

@ -77,6 +77,23 @@ class DefaultTempFileCreationStrategyTest {
}
}
@Test
void testProvidedDirThreadLocal() throws IOException {
DefaultTempFileCreationStrategy parentStrategy = new DefaultTempFileCreationStrategy();
File dir = parentStrategy.createTempDirectory("testProvidedDir");
assertNotNull(dir, "Failed to create temp directory");
try {
assertTrue(Files.isDirectory(dir.toPath()), "File is not a directory: " + dir);
DefaultTempFileCreationStrategy testStrategy = new DefaultTempFileCreationStrategy(dir);
TempFile.setThreadLocalTempFileCreationStrategy(testStrategy);
checkGetFileAndPath(dir.toPath());
} finally {
// Clean up the directory after the test
FileUtils.deleteDirectory(dir);
TempFile.setThreadLocalTempFileCreationStrategy(null);
}
}
@Test
void testProvidedDirNotExists() throws IOException {
DefaultTempFileCreationStrategy parentStrategy = new DefaultTempFileCreationStrategy();
@ -127,6 +144,25 @@ class DefaultTempFileCreationStrategyTest {
}
}
private static void checkGetFileAndPath(Path path) throws IOException {
File file = TempFile.createTempFile("POITest", ".tmp");
try {
if (path != null) {
assertTrue(file.toPath().startsWith(path),
"File path does not start with expected path: " + path);
}
assertTrue(file.getParentFile().exists(),
"Failed for " + file.getParentFile());
assertTrue(file.exists(),
"Failed for " + file);
} finally {
assertTrue(file.delete());
}
}
@Test
void testDefaultDir() throws IOException {
DefaultTempFileCreationStrategy strategy = new DefaultTempFileCreationStrategy();