Merge pull request #5453 from eclipse/jetty-9.4.x-5451-general-tempdir-cleanup

Issue #5451 - Cleanup of temp file usages.
This commit is contained in:
Joakim Erdfelt 2020-10-16 07:28:32 -05:00 committed by GitHub
commit 820c79ba5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 447 additions and 412 deletions

View File

@ -18,8 +18,9 @@
package org.eclipse.jetty.embedded;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@ -120,8 +121,8 @@ public class ManyHandlers
gzipHandler.addIncludedMimeTypes("text/html");
// configure request logging
File requestLogFile = File.createTempFile("demo", "log");
CustomRequestLog ncsaLog = new CustomRequestLog(requestLogFile.getAbsolutePath());
Path requestLogFile = Files.createTempFile("demo", "log");
CustomRequestLog ncsaLog = new CustomRequestLog(requestLogFile.toString());
server.setRequestLog(ncsaLog);
// create the handler collections

View File

@ -31,6 +31,7 @@ import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@ -41,6 +42,7 @@ import javax.servlet.http.Part;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.ByteArrayOutputStream2;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.LazyList;
import org.eclipse.jetty.util.MultiException;
import org.eclipse.jetty.util.MultiMap;
@ -67,7 +69,6 @@ public class MultiPartFormInputStream
private Throwable _err;
private File _tmpDir;
private File _contextTmpDir;
private boolean _deleteOnExit;
private boolean _writeFilesWithFilenames;
private boolean _parsed;
private int _bufferSize = 16 * 1024;
@ -151,19 +152,11 @@ public class MultiPartFormInputStream
protected void createFile() throws IOException
{
/*
* Some statics just to make the code below easier to understand This get optimized away during the compile anyway
*/
final boolean USER = true;
final boolean WORLD = false;
Path parent = MultiPartFormInputStream.this._tmpDir.toPath();
Path tempFile = Files.createTempFile(parent, "MultiPart", "", IO.getUserOnlyFileAttribute(parent));
_file = tempFile.toFile();
_file = File.createTempFile("MultiPart", "", MultiPartFormInputStream.this._tmpDir);
_file.setReadable(false, WORLD); // (reset) disable it for everyone first
_file.setReadable(true, USER); // enable for user only
if (_deleteOnExit)
_file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(_file);
OutputStream fos = Files.newOutputStream(tempFile, StandardOpenOption.WRITE);
BufferedOutputStream bos = new BufferedOutputStream(fos);
if (_size > 0 && _out != null)
@ -757,9 +750,13 @@ public class MultiPartFormInputStream
}
}
/**
* @deprecated no replacement provided.
*/
@Deprecated
public void setDeleteOnExit(boolean deleteOnExit)
{
_deleteOnExit = deleteOnExit;
// does nothing.
}
public void setWriteFilesWithFilenames(boolean writeFilesWithFilenames)
@ -772,9 +769,13 @@ public class MultiPartFormInputStream
return _writeFilesWithFilenames;
}
/**
* @deprecated no replacement provided
*/
@Deprecated
public boolean isDeleteOnExit()
{
return _deleteOnExit;
return false;
}
private static String value(String nameEqualsValue)

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
@ -35,17 +34,21 @@ import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
@ -54,10 +57,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@ExtendWith(WorkDirExtension.class)
public class IOTest
{
public WorkDir workDir;
@Test
public void testIO() throws Exception
{
@ -96,7 +101,6 @@ public class IOTest
// but cannot write
Assertions.assertThrows(SocketException.class, () -> client.getOutputStream().write(1));
// but can still write in opposite direction.
server.getOutputStream().write(1);
assertEquals(1, client.getInputStream().read());
@ -419,13 +423,9 @@ public class IOTest
@Test
public void testGatherWrite() throws Exception
{
File dir = MavenTestingUtils.getTargetTestingDir();
if (!dir.exists())
dir.mkdir();
File file = File.createTempFile("test", ".txt", dir);
file.deleteOnExit();
FileChannel out = FileChannel.open(file.toPath(),
Path dir = workDir.getEmptyPathDir();
Path file = Files.createTempFile(dir, "test", ".txt");
FileChannel out = FileChannel.open(file,
StandardOpenOption.CREATE,
StandardOpenOption.READ,
StandardOpenOption.WRITE,

View File

@ -27,6 +27,8 @@ import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
@ -54,6 +56,8 @@ import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.log.Log;
@ -64,6 +68,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
@ -81,9 +86,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
// @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck
@ExtendWith(WorkDirExtension.class)
public class RequestTest
{
private static final Logger LOG = Log.getLogger(RequestTest.class);
public WorkDir workDir;
private Server _server;
private LocalConnector _connector;
private RequestHandler _handler;
@ -335,20 +342,14 @@ public class RequestTest
@Test
public void testMultiPart() throws Exception
{
final File testTmpDir = File.createTempFile("reqtest", null);
if (testTmpDir.exists())
testTmpDir.delete();
testTmpDir.mkdir();
testTmpDir.deleteOnExit();
assertTrue(testTmpDir.list().length == 0);
Path testTmpDir = workDir.getEmptyPathDir();
ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/foo");
contextHandler.setResourceBase(".");
contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir));
contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir.toFile()));
contextHandler.addEventListener(new MultiPartCleanerListener()
{
@Override
public void requestDestroyed(ServletRequestEvent sre)
{
@ -356,12 +357,11 @@ public class RequestTest
assertNotNull(m);
ContextHandler.Context c = m.getContext();
assertNotNull(c);
assertTrue(c == sre.getServletContext());
assertTrue(!m.isEmpty());
assertTrue(testTmpDir.list().length == 2);
assertSame(c, sre.getServletContext());
assertFalse(m.isEmpty());
assertThat("File count in temp dir", getFileCount(testTmpDir), is(2L));
super.requestDestroyed(sre);
String[] files = testTmpDir.list();
assertTrue(files.length == 0);
assertThat("File count in temp dir", getFileCount(testTmpDir), is(0L));
}
});
_server.stop();
@ -395,20 +395,14 @@ public class RequestTest
@Test
public void testUtilMultiPart() throws Exception
{
final File testTmpDir = File.createTempFile("reqtest", null);
if (testTmpDir.exists())
testTmpDir.delete();
testTmpDir.mkdir();
testTmpDir.deleteOnExit();
assertTrue(testTmpDir.list().length == 0);
Path testTmpDir = workDir.getEmptyPathDir();
ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/foo");
contextHandler.setResourceBase(".");
contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir));
contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir.toFile()));
contextHandler.addEventListener(new MultiPartCleanerListener()
{
@Override
public void requestDestroyed(ServletRequestEvent sre)
{
@ -416,12 +410,11 @@ public class RequestTest
assertNotNull(m);
ContextHandler.Context c = m.getContext();
assertNotNull(c);
assertTrue(c == sre.getServletContext());
assertTrue(!m.isEmpty());
assertTrue(testTmpDir.list().length == 2);
assertSame(c, sre.getServletContext());
assertFalse(m.isEmpty());
assertThat("File count in temp dir", getFileCount(testTmpDir), is(2L));
super.requestDestroyed(sre);
String[] files = testTmpDir.list();
assertTrue(files.length == 0);
assertThat("File count in temp dir", getFileCount(testTmpDir), is(0L));
}
});
_server.stop();
@ -458,17 +451,12 @@ public class RequestTest
@Test
public void testHttpMultiPart() throws Exception
{
final File testTmpDir = File.createTempFile("reqtest", null);
if (testTmpDir.exists())
testTmpDir.delete();
testTmpDir.mkdir();
testTmpDir.deleteOnExit();
assertTrue(testTmpDir.list().length == 0);
Path testTmpDir = workDir.getEmptyPathDir();
ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/foo");
contextHandler.setResourceBase(".");
contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir));
contextHandler.setHandler(new MultiPartRequestHandler(testTmpDir.toFile()));
_server.stop();
_server.setHandler(contextHandler);
@ -503,17 +491,12 @@ public class RequestTest
public void testBadMultiPart() throws Exception
{
//a bad multipart where one of the fields has no name
final File testTmpDir = File.createTempFile("badmptest", null);
if (testTmpDir.exists())
testTmpDir.delete();
testTmpDir.mkdir();
testTmpDir.deleteOnExit();
assertTrue(testTmpDir.list().length == 0);
Path testTmpDir = workDir.getEmptyPathDir();
ContextHandler contextHandler = new ContextHandler();
contextHandler.setContextPath("/foo");
contextHandler.setResourceBase(".");
contextHandler.setHandler(new BadMultiPartRequestHandler(testTmpDir));
contextHandler.setHandler(new BadMultiPartRequestHandler(testTmpDir.toFile()));
contextHandler.addEventListener(new MultiPartCleanerListener()
{
@ -524,10 +507,9 @@ public class RequestTest
assertNotNull(m);
ContextHandler.Context c = m.getContext();
assertNotNull(c);
assertTrue(c == sre.getServletContext());
assertSame(c, sre.getServletContext());
super.requestDestroyed(sre);
String[] files = testTmpDir.list();
assertTrue(files.length == 0);
assertThat("File count in temp dir", getFileCount(testTmpDir), is(0L));
}
});
_server.stop();
@ -1853,6 +1835,18 @@ public class RequestTest
assertEquals(0, request.getParameterMap().size());
}
private static long getFileCount(Path path)
{
try
{
return Files.list(path).count();
}
catch (IOException e)
{
throw new RuntimeException("Unable to get file list count: " + path, e);
}
}
interface RequestTester
{
boolean check(HttpServletRequest request, HttpServletResponse response) throws IOException;

View File

@ -38,9 +38,12 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.resource.Resource;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
@ -50,8 +53,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(WorkDirExtension.class)
public class ContextHandlerTest
{
public WorkDir workDir;
@Test
public void testGetResourcePathsWhenSuppliedPathEndsInSlash() throws Exception
{
@ -796,24 +802,14 @@ public class ContextHandlerTest
private File setupTestDirectory() throws IOException
{
File tmpDir = new File(System.getProperty("basedir", ".") + "/target/tmp/ContextHandlerTest");
tmpDir = tmpDir.getCanonicalFile();
if (!tmpDir.exists())
assertTrue(tmpDir.mkdirs());
File tmp = File.createTempFile("cht", null, tmpDir);
assertTrue(tmp.delete());
assertTrue(tmp.mkdir());
tmp.deleteOnExit();
File root = new File(tmp, getClass().getName());
assertTrue(root.mkdir());
Path root = workDir.getEmptyPathDir();
File webInf = new File(root, "WEB-INF");
assertTrue(webInf.mkdir());
Path webInfDir = root.resolve("WEB-INF");
FS.ensureDirExists(webInfDir);
FS.ensureDirExists(webInfDir.resolve("jsp"));
FS.touch(webInfDir.resolve("web.xml"));
assertTrue(new File(webInf, "jsp").mkdir());
assertTrue(new File(webInf, "web.xml").createNewFile());
return root;
return root.toFile();
}
private void checkWildcardHost(boolean succeed, Server server, String[] contextHosts, String[] requestHosts) throws Exception

View File

@ -157,6 +157,11 @@ public class ServletTester extends ContainerLifeCycle
return _context.getBaseResource();
}
public void setBaseResource(Resource resource)
{
_context.setBaseResource(resource);
}
public String getResourceBase()
{
return _context.getResourceBase();

View File

@ -25,6 +25,10 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@ -212,8 +216,8 @@ public class PutFilter implements Filter
if (_putAtomic)
{
File tmp = File.createTempFile(file.getName(), null, _tmpdir);
try (OutputStream out = new FileOutputStream(tmp, false))
Path tmp = Files.createTempFile(_tmpdir.toPath(), file.getName(), null);
try (OutputStream out = Files.newOutputStream(tmp, StandardOpenOption.WRITE))
{
if (toRead >= 0)
IO.copy(in, out, toRead);
@ -221,8 +225,7 @@ public class PutFilter implements Filter
IO.copy(in, out);
}
if (!tmp.renameTo(file))
throw new IOException("rename from " + tmp + " to " + file + " failed");
Files.move(tmp, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
else
{

View File

@ -25,6 +25,7 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
@ -45,12 +46,16 @@ import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.FilterMapping;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.ReadLineInputStream;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.eclipse.jetty.util.resource.PathResource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
@ -61,9 +66,10 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
// @checkstyle-disable-check : AvoidEscapedUnicodeCharactersCheck
@ExtendWith(WorkDirExtension.class)
public class MultipartFilterTest
{
private File _dir;
public WorkDir workDir;
private ServletTester tester;
FilterHolder multipartFilter;
@ -157,16 +163,12 @@ public class MultipartFilterTest
@BeforeEach
public void setUp() throws Exception
{
_dir = File.createTempFile("testmultupart", null);
assertTrue(_dir.delete());
assertTrue(_dir.mkdir());
_dir.deleteOnExit();
assertTrue(_dir.isDirectory());
Path root = workDir.getEmptyPathDir();
tester = new ServletTester("/context");
tester.getContext().setResourceBase(_dir.getCanonicalPath());
tester.getContext().setBaseResource(new PathResource(root));
tester.getContext().addServlet(TestServlet.class, "/");
tester.getContext().setAttribute("javax.servlet.context.tempdir", _dir);
tester.getContext().setAttribute("javax.servlet.context.tempdir", root.toFile());
multipartFilter = tester.getContext().addFilter(MultiPartFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
multipartFilter.setInitParameter("deleteFiles", "true");
multipartFilter.setInitParameter("fileOutputBuffer", "1"); //write a file if there's more than 1 byte content

View File

@ -18,54 +18,59 @@
package org.eclipse.jetty.servlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletTester;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.resource.PathResource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.in;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ExtendWith(WorkDirExtension.class)
public class PutFilterTest
{
private File _dir;
public WorkDir workDir;
private Path root;
private ServletTester tester;
@BeforeEach
public void setUp() throws Exception
{
_dir = File.createTempFile("testPutFilter", null);
assertTrue(_dir.delete());
assertTrue(_dir.mkdir());
_dir.deleteOnExit();
assertTrue(_dir.isDirectory());
root = workDir.getEmptyPathDir();
tester = new ServletTester("/context");
tester.setResourceBase(_dir.getCanonicalPath());
tester.setBaseResource(new PathResource(root));
tester.addServlet(org.eclipse.jetty.servlet.DefaultServlet.class, "/");
FilterHolder holder = tester.addFilter(PutFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
holder.setInitParameter("delAllowed", "true");
tester.setAttribute(ServletContext.TEMPDIR, workDir.getPath().toFile());
// Bloody Windows does not allow file renaming
if (!System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"))
holder.setInitParameter("putAtomic", "true");
@ -76,7 +81,6 @@ public class PutFilterTest
public void tearDown() throws Exception
{
tester.stop();
IO.delete(_dir);
}
@Test
@ -103,9 +107,9 @@ public class PutFilterTest
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_CREATED, response.getStatus());
File file = new File(_dir, "file.txt");
assertTrue(file.exists());
assertEquals(data0, IO.toString(new FileInputStream(file)));
Path file = root.resolve("file.txt");
assertTrue(Files.exists(file));
assertEquals(data0, IO.toString(file, UTF_8));
// test GET1
request.setMethod("GET");
@ -125,9 +129,9 @@ public class PutFilterTest
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
file = new File(_dir, "file.txt");
assertTrue(file.exists());
assertEquals(data1, IO.toString(new FileInputStream(file)));
file = root.resolve("file.txt");
assertTrue(Files.exists(file));
assertEquals(data1, IO.toString(file, UTF_8));
// test PUT2
request.setMethod("PUT");
@ -193,19 +197,16 @@ public class PutFilterTest
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_CREATED, response.getStatus());
File file = new File(_dir, "file.txt");
assertTrue(file.exists());
try (InputStream fis = new FileInputStream(file))
{
assertEquals(data1, IO.toString(fis));
}
Path file = root.resolve("file.txt");
assertTrue(Files.exists(file));
assertEquals(data1, IO.toString(file, UTF_8));
request.setMethod("DELETE");
request.setURI("/context/file.txt");
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
assertTrue(!file.exists());
assertFalse(Files.exists(file));
request.setMethod("DELETE");
request.setURI("/context/file.txt");
@ -232,12 +233,9 @@ public class PutFilterTest
assertEquals(HttpServletResponse.SC_CREATED, response.getStatus());
File file = new File(_dir, "file.txt");
assertTrue(file.exists());
try (InputStream fis = new FileInputStream(file))
{
assertEquals(data1, IO.toString(fis));
}
Path file = root.resolve("file.txt");
assertTrue(Files.exists(file));
assertEquals(data1, IO.toString(file, UTF_8));
request.setMethod("MOVE");
request.setURI("/context/file.txt");
@ -245,10 +243,10 @@ public class PutFilterTest
response = HttpTester.parseResponse(tester.getResponses(request.generate()));
assertEquals(HttpServletResponse.SC_NO_CONTENT, response.getStatus());
assertTrue(!file.exists());
assertFalse(Files.exists(file));
File nFile = new File(_dir, "blah.txt");
assertTrue(nFile.exists());
Path nFile = root.resolve("blah.txt");
assertTrue(Files.exists(nFile));
}
@Test

View File

@ -34,6 +34,16 @@ import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.charset.Charset;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.DosFileAttributeView;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.HashSet;
import java.util.Objects;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -47,6 +57,24 @@ public class IO
{
private static final Logger LOG = Log.getLogger(IO.class);
private static final FileAttribute<?>[] NO_FILE_ATTRIBUTES = new FileAttribute[0];
private static final FileAttribute<?>[] USER_ONLY_POSIX_FILE_ATTRIBUTES =
new FileAttribute[]{
PosixFilePermissions.asFileAttribute(
new HashSet<PosixFilePermission>()
{
{
add(PosixFilePermission.OWNER_EXECUTE);
add(PosixFilePermission.OWNER_READ);
add(PosixFilePermission.OWNER_WRITE);
// we don't add GROUP or OTHER write perms here.
add(PosixFilePermission.GROUP_READ);
add(PosixFilePermission.OTHERS_READ);
}
}
)
};
public static final String
CRLF = "\r\n";
@ -279,6 +307,21 @@ public class IO
}
}
/**
* Read Path to string.
*
* @param path the path to read from (until EOF)
* @param charset the charset to read with
* @return the String parsed from path (default Charset)
* @throws IOException if unable to read the path (or handle the charset)
*/
public static String toString(Path path, Charset charset)
throws IOException
{
byte[] buf = Files.readAllBytes(path);
return new String(buf, charset);
}
/**
* Read input stream to string.
*
@ -419,6 +462,58 @@ public class IO
close((Closeable)writer);
}
/**
* Get the array of {@link FileAttribute} values for the provided path
* that will set the path to Full Read/Write for the user running Jetty,
* but Readonly for other users.
* <p>
* For Unix, that's means {@link java.nio.file.attribute.PosixFileAttributes}
* where the World and Other groups have their read / write flags removed.
* </p>
* <p>
* For Windows / Dos, that means {@link java.nio.file.attribute.DosFileAttributes}
* </p>
*/
public static FileAttribute<?>[] getUserOnlyFileAttribute(Path path)
{
FileStore fileStore = null;
try
{
// Obtain a reference to the FileStore to know what kind of read-only we are capable of.
fileStore = Files.getFileStore(Objects.requireNonNull(path));
if (fileStore == null)
{
// Not on a properly implemented FileStore (seen with 3rd party FileStore implementations)
// We cannot do anything in this case, so just return.
return NO_FILE_ATTRIBUTES;
}
if (fileStore.supportsFileAttributeView(DosFileAttributeView.class))
{
// We are on a Windows / DOS filesystem.
// It might support ACL, but we don't attempt to support that here.
return NO_FILE_ATTRIBUTES;
}
if (fileStore.supportsFileAttributeView(PosixFileAttributeView.class))
{
// We are on a Unix / Linux / OSX system
return USER_ONLY_POSIX_FILE_ATTRIBUTES;
}
// If we reached this point, we have a Path on a FileSystem / FileStore that we cannot control.
// So skip the attempt to set readable.
}
catch (IOException e)
{
if (LOG.isDebugEnabled())
LOG.debug("Unable to determine attribute types on path: {}", path, e);
}
return NO_FILE_ATTRIBUTES;
}
public static byte[] readBytes(InputStream in)
throws IOException
{

View File

@ -33,6 +33,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
@ -72,7 +73,6 @@ public class MultiPartInputStreamParser
protected Exception _err;
protected File _tmpDir;
protected File _contextTmpDir;
protected boolean _deleteOnExit;
protected boolean _writeFilesWithFilenames;
protected boolean _parsed;
@ -190,18 +190,11 @@ public class MultiPartInputStreamParser
protected void createFile()
throws IOException
{
/* Some statics just to make the code below easier to understand
* This get optimized away during the compile anyway */
final boolean USER = true;
final boolean WORLD = false;
Path parent = MultiPartInputStreamParser.this._tmpDir.toPath();
Path tempFile = Files.createTempFile(parent, "MultiPart", "", IO.getUserOnlyFileAttribute(parent));
_file = tempFile.toFile();
_file = File.createTempFile("MultiPart", "", MultiPartInputStreamParser.this._tmpDir);
_file.setReadable(false, WORLD); // (reset) disable it for everyone first
_file.setReadable(true, USER); // enable for user only
if (_deleteOnExit)
_file.deleteOnExit();
FileOutputStream fos = new FileOutputStream(_file);
OutputStream fos = Files.newOutputStream(tempFile, StandardOpenOption.WRITE);
BufferedOutputStream bos = new BufferedOutputStream(fos);
if (_size > 0 && _out != null)
@ -864,9 +857,13 @@ public class MultiPartInputStreamParser
}
}
/**
* @deprecated no replacement offered.
*/
@Deprecated
public void setDeleteOnExit(boolean deleteOnExit)
{
_deleteOnExit = deleteOnExit;
// does nothing
}
public void setWriteFilesWithFilenames(boolean writeFilesWithFilenames)
@ -879,9 +876,13 @@ public class MultiPartInputStreamParser
return _writeFilesWithFilenames;
}
/**
* @deprecated no replacement offered.
*/
@Deprecated
public boolean isDeleteOnExit()
{
return _deleteOnExit;
return false;
}
private String value(String nameEqualsValue)

View File

@ -18,26 +18,18 @@
package org.eclipse.jetty.server.session;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* ClusteredOrphanedSessionTest
*/
@ExtendWith(WorkDirExtension.class)
public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessionTest
{
@BeforeEach
public void before() throws Exception
{
FileTestHelper.setup();
}
@AfterEach
public void after()
{
FileTestHelper.teardown();
}
public WorkDir workDir;
/**
* @see org.eclipse.jetty.server.session.AbstractTestBase#createSessionDataStoreFactory()
@ -45,7 +37,7 @@ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessi
@Override
public SessionDataStoreFactory createSessionDataStoreFactory()
{
return FileTestHelper.newSessionDataStoreFactory();
return FileTestHelper.newSessionDataStoreFactory(workDir);
}
@Test

View File

@ -18,44 +18,36 @@
package org.eclipse.jetty.server.session;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* FileSessionDataStoreTest
*/
@ExtendWith(WorkDirExtension.class)
public class FileSessionDataStoreTest extends AbstractSessionDataStoreTest
{
@BeforeEach
public void before() throws Exception
{
FileTestHelper.setup();
}
@AfterEach
public void after()
{
FileTestHelper.teardown();
}
public WorkDir workDir;
@Override
public SessionDataStoreFactory createSessionDataStoreFactory()
{
return FileTestHelper.newSessionDataStoreFactory();
return FileTestHelper.newSessionDataStoreFactory(workDir);
}
@Override
public void persistSession(SessionData data) throws Exception
{
FileTestHelper.createFile(data.getId(), data.getContextPath(), data.getVhost(), data.getLastNode(), data.getCreated(),
FileTestHelper.createFile(workDir, data.getId(), data.getContextPath(), data.getVhost(), data.getLastNode(), data.getCreated(),
data.getAccessed(), data.getLastAccessed(), data.getMaxInactiveMs(), data.getExpiry(), data.getCookieSet(), data.getAllAttributes());
}
@Override
public void persistUnreadableSession(SessionData data) throws Exception
{
FileTestHelper.createFile(data.getId(), data.getContextPath(), data.getVhost(), data.getLastNode(), data.getCreated(),
FileTestHelper.createFile(workDir, data.getId(), data.getContextPath(), data.getVhost(), data.getLastNode(), data.getCreated(),
data.getAccessed(), data.getLastAccessed(), data.getMaxInactiveMs(), data.getExpiry(), data.getCookieSet(), null);
}
@ -66,7 +58,7 @@ public class FileSessionDataStoreTest extends AbstractSessionDataStoreTest
Thread.currentThread().setContextClassLoader(_contextClassLoader);
try
{
return (FileTestHelper.getFile(data.getId()) != null);
return (FileTestHelper.getFile(workDir, data.getId()) != null);
}
finally
{
@ -84,7 +76,7 @@ public class FileSessionDataStoreTest extends AbstractSessionDataStoreTest
Thread.currentThread().setContextClassLoader(_contextClassLoader);
try
{
return FileTestHelper.checkSessionPersisted(data);
return FileTestHelper.checkSessionPersisted(workDir, data);
}
catch (Throwable e)
{

View File

@ -21,19 +21,23 @@ package org.eclipse.jetty.server.session;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.util.ClassLoadingObjectInputStream;
import org.eclipse.jetty.util.IO;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@ -42,116 +46,54 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
public class FileTestHelper
{
static int __workers = 0;
static File _tmpDir;
public static void setup()
throws Exception
public static File getFile(WorkDir workDir, String sessionId) throws IOException
{
_tmpDir = File.createTempFile("file", null);
_tmpDir.delete();
_tmpDir.mkdirs();
_tmpDir.deleteOnExit();
}
public static void teardown()
{
IO.delete(_tmpDir);
_tmpDir = null;
}
public static void assertStoreDirEmpty(boolean isEmpty)
{
assertNotNull(_tmpDir);
assertTrue(_tmpDir.exists());
String[] files = _tmpDir.list();
if (isEmpty)
{
if (files != null)
assertEquals(0, files.length);
}
else
{
assertNotNull(files);
assertFalse(files.length == 0);
}
}
public static File getFile(String sessionId)
{
assertNotNull(_tmpDir);
assertTrue(_tmpDir.exists());
String[] files = _tmpDir.list();
assertNotNull(files);
String fname = null;
for (String name : files)
{
if (name.contains(sessionId))
{
fname = name;
break;
}
}
if (fname != null)
return new File(_tmpDir, fname);
Optional<Path> sessionPath = Files.list(workDir.getPath())
.filter((path) -> path.getFileName().toString().contains(sessionId))
.findFirst();
if (sessionPath.isPresent())
return sessionPath.get().toFile();
return null;
}
public static void assertSessionExists(String sessionId, boolean exists)
public static void assertSessionExists(WorkDir workDir, String sessionId, boolean exists) throws IOException
{
assertNotNull(_tmpDir);
assertTrue(_tmpDir.exists());
String[] files = _tmpDir.list();
assertNotNull(files);
Optional<Path> sessionPath = Files.list(workDir.getPath())
.filter((path) -> path.getFileName().toString().contains(sessionId))
.findFirst();
if (exists)
assertFalse(files.length == 0);
boolean found = false;
for (String name : files)
{
if (name.contains(sessionId))
{
found = true;
break;
}
}
if (exists)
assertTrue(found);
assertTrue(sessionPath.isPresent());
else
assertFalse(found);
assertFalse(sessionPath.isPresent());
}
public static void assertFileExists(String filename, boolean exists)
public static void assertFileExists(WorkDir workDir, String filename, boolean exists)
{
assertNotNull(_tmpDir);
assertTrue(_tmpDir.exists());
File file = new File(_tmpDir, filename);
Path path = workDir.getPath().resolve(filename);
if (exists)
assertTrue(file.exists());
assertTrue(Files.exists(path), "File should exist: " + path);
else
assertFalse(file.exists());
assertFalse(Files.exists(path), "File should NOT exist: " + path);
}
public static void createFile(String filename)
public static void createFile(WorkDir workDir, String filename)
throws IOException
{
assertNotNull(_tmpDir);
assertTrue(_tmpDir.exists());
File file = new File(_tmpDir, filename);
Files.deleteIfExists(file.toPath());
file.createNewFile();
Path path = workDir.getPath().resolve(filename);
Files.deleteIfExists(path);
FS.touch(path);
}
public static void createFile(String id, String contextPath, String vhost,
public static void createFile(WorkDir workDir, String id, String contextPath, String vhost,
String lastNode, long created, long accessed,
long lastAccessed, long maxIdle, long expiry,
long cookieSet, Map<String, Object> attributes)
throws Exception
{
String filename = "" + expiry + "_" + contextPath + "_" + vhost + "_" + id;
File file = new File(_tmpDir, filename);
try (FileOutputStream fos = new FileOutputStream(file, false);
Path path = workDir.getPath().resolve(filename);
try (OutputStream fos = Files.newOutputStream(path);
DataOutputStream out = new DataOutputStream(fos))
{
out.writeUTF(id);
@ -174,14 +116,15 @@ public class FileTestHelper
}
}
public static boolean checkSessionPersisted(SessionData data)
public static boolean checkSessionPersisted(WorkDir workDir, SessionData data)
throws Exception
{
String filename = "" + data.getExpiry() + "_" + data.getContextPath() + "_" + data.getVhost() + "_" + data.getId();
File file = new File(_tmpDir, filename);
assertTrue(file.exists());
Path file = workDir.getPath().resolve(filename);
try (FileInputStream in = new FileInputStream(file);
assertTrue(Files.exists(file));
try (InputStream in = Files.newInputStream(file);
DataInputStream di = new DataInputStream(in))
{
String id = di.readUTF();
@ -213,44 +156,35 @@ public class FileTestHelper
//same number of attributes
assertEquals(data.getAllAttributes().size(), tmp.getAllAttributes().size());
//same keys
assertTrue(data.getKeys().equals(tmp.getAllAttributes().keySet()));
assertEquals(tmp.getAllAttributes().keySet(), data.getKeys());
//same values
for (String name : data.getKeys())
{
assertTrue(data.getAttribute(name).equals(tmp.getAttribute(name)));
assertEquals(tmp.getAttribute(name), data.getAttribute(name));
}
}
return true;
}
public static void deleteFile(String sessionId)
public static void deleteFile(WorkDir workDir, String sessionId) throws IOException
{
assertNotNull(_tmpDir);
assertTrue(_tmpDir.exists());
String[] files = _tmpDir.list();
assertNotNull(files);
assertFalse(files.length == 0);
String filename = null;
for (String name : files)
// Collect
List<Path> matches = Files.list(workDir.getPath())
.filter((path) -> path.getFileName().toString().contains(sessionId))
.collect(Collectors.toList());
// Delete outside of lambda
for (Path path : matches)
{
if (name.contains(sessionId))
{
filename = name;
break;
}
}
if (filename != null)
{
File f = new File(_tmpDir, filename);
assertTrue(f.delete());
FS.deleteFile(path);
}
}
public static FileSessionDataStoreFactory newSessionDataStoreFactory()
public static FileSessionDataStoreFactory newSessionDataStoreFactory(WorkDir workDir)
{
FileSessionDataStoreFactory storeFactory = new FileSessionDataStoreFactory();
storeFactory.setStoreDir(_tmpDir);
storeFactory.setStoreDir(workDir.getPath().toFile());
return storeFactory;
}
}

View File

@ -21,11 +21,12 @@ package org.eclipse.jetty.server.session;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StacklessLogging;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@ -36,24 +37,15 @@ import static org.junit.jupiter.api.Assertions.fail;
/**
* TestFileSessions
*/
@ExtendWith(WorkDirExtension.class)
public class TestFileSessions extends AbstractTestBase
{
@BeforeEach
public void before() throws Exception
{
FileTestHelper.setup();
}
@AfterEach
public void after()
{
FileTestHelper.teardown();
}
public WorkDir workDir;
@Override
public SessionDataStoreFactory createSessionDataStoreFactory()
{
return FileTestHelper.newSessionDataStoreFactory();
return FileTestHelper.newSessionDataStoreFactory(workDir);
}
/**
@ -74,7 +66,7 @@ public class TestFileSessions extends AbstractTestBase
store.initialize(sessionContext);
//make a file for foobar context
FileTestHelper.createFile((System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) + "__foobar_0.0.0.0_1234");
FileTestHelper.createFile(workDir, (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) + "__foobar_0.0.0.0_1234");
store.start();
@ -208,7 +200,6 @@ public class TestFileSessions extends AbstractTestBase
@Test
public void testSweep() throws Exception
{
//create the SessionDataStore
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/test");
@ -221,41 +212,41 @@ public class TestFileSessions extends AbstractTestBase
store.start();
//create file not for our context that expired long ago and should be removed by sweep
FileTestHelper.createFile("101__foobar_0.0.0.0_sessiona");
FileTestHelper.assertSessionExists("sessiona", true);
FileTestHelper.createFile(workDir, "101__foobar_0.0.0.0_sessiona");
FileTestHelper.assertSessionExists(workDir, "sessiona", true);
//create a file not for our context that is not expired and should be ignored
String nonExpiredForeign = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) + "__foobar_0.0.0.0_sessionb";
FileTestHelper.createFile(nonExpiredForeign);
FileTestHelper.assertFileExists(nonExpiredForeign, true);
FileTestHelper.createFile(workDir, nonExpiredForeign);
FileTestHelper.assertFileExists(workDir, nonExpiredForeign, true);
//create a file not for our context that is recently expired, a thus ignored by sweep
String expiredForeign = (System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1)) + "__foobar_0.0.0.0_sessionc";
FileTestHelper.createFile(expiredForeign);
FileTestHelper.assertFileExists(expiredForeign, true);
FileTestHelper.createFile(workDir, expiredForeign);
FileTestHelper.assertFileExists(workDir, expiredForeign, true);
//create a file that is not a session file, it should be ignored
FileTestHelper.createFile("whatever.txt");
FileTestHelper.assertFileExists("whatever.txt", true);
FileTestHelper.createFile(workDir, "whatever.txt");
FileTestHelper.assertFileExists(workDir, "whatever.txt", true);
//create a file that is not a valid session filename, should be ignored
FileTestHelper.createFile("nonNumber__0.0.0.0_spuriousFile");
FileTestHelper.assertFileExists("nonNumber__0.0.0.0_spuriousFile", true);
FileTestHelper.createFile(workDir, "nonNumber__0.0.0.0_spuriousFile");
FileTestHelper.assertFileExists(workDir, "nonNumber__0.0.0.0_spuriousFile", true);
//create a file that is a non-expired session file for our context that should be ignored
String nonExpired = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) + "__test_0.0.0.0_sessionb";
FileTestHelper.createFile(nonExpired);
FileTestHelper.assertFileExists(nonExpired, true);
FileTestHelper.createFile(workDir, nonExpired);
FileTestHelper.assertFileExists(workDir, nonExpired, true);
//create a file that is a never-expire session file for our context that should be ignored
String neverExpired = "0__test_0.0.0.0_sessionc";
FileTestHelper.createFile(neverExpired);
FileTestHelper.assertFileExists(neverExpired, true);
FileTestHelper.createFile(workDir, neverExpired);
FileTestHelper.assertFileExists(workDir, neverExpired, true);
//create a file that is a never-expire session file for another context that should be ignored
String foreignNeverExpired = "0__other_0.0.0.0_sessionc";
FileTestHelper.createFile(foreignNeverExpired);
FileTestHelper.assertFileExists(foreignNeverExpired, true);
FileTestHelper.createFile(workDir, foreignNeverExpired);
FileTestHelper.assertFileExists(workDir, foreignNeverExpired, true);
//sweep - we're expecting a debug log with exception stacktrace due to file named
//nonNumber__0.0.0.0_spuriousFile so suppress it
@ -265,14 +256,14 @@ public class TestFileSessions extends AbstractTestBase
}
//check results
FileTestHelper.assertSessionExists("sessiona", false);
FileTestHelper.assertFileExists("whatever.txt", true);
FileTestHelper.assertFileExists("nonNumber__0.0.0.0_spuriousFile", true);
FileTestHelper.assertFileExists(nonExpired, true);
FileTestHelper.assertFileExists(nonExpiredForeign, true);
FileTestHelper.assertFileExists(expiredForeign, true);
FileTestHelper.assertFileExists(neverExpired, true);
FileTestHelper.assertFileExists(foreignNeverExpired, true);
FileTestHelper.assertSessionExists(workDir, "sessiona", false);
FileTestHelper.assertFileExists(workDir, "whatever.txt", true);
FileTestHelper.assertFileExists(workDir, "nonNumber__0.0.0.0_spuriousFile", true);
FileTestHelper.assertFileExists(workDir, nonExpired, true);
FileTestHelper.assertFileExists(workDir, nonExpiredForeign, true);
FileTestHelper.assertFileExists(workDir, expiredForeign, true);
FileTestHelper.assertFileExists(workDir, neverExpired, true);
FileTestHelper.assertFileExists(workDir, foreignNeverExpired, true);
}
/**
@ -292,54 +283,54 @@ public class TestFileSessions extends AbstractTestBase
store.initialize(sessionContext);
//create file not for our context that expired long ago and should be removed
FileTestHelper.createFile("101_foobar_0.0.0.0_sessiona");
FileTestHelper.assertSessionExists("sessiona", true);
FileTestHelper.createFile(workDir, "101_foobar_0.0.0.0_sessiona");
FileTestHelper.assertSessionExists(workDir, "sessiona", true);
//create a file not for our context that is not expired and should be ignored
String nonExpiredForeign = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) + "_foobar_0.0.0.0_sessionb";
FileTestHelper.createFile(nonExpiredForeign);
FileTestHelper.assertFileExists(nonExpiredForeign, true);
FileTestHelper.createFile(workDir, nonExpiredForeign);
FileTestHelper.assertFileExists(workDir, nonExpiredForeign, true);
//create a file not for our context that is recently expired, a thus ignored
String expiredForeign = (System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(1)) + "_foobar_0.0.0.0_sessionc";
FileTestHelper.createFile(expiredForeign);
FileTestHelper.assertFileExists(expiredForeign, true);
FileTestHelper.createFile(workDir, expiredForeign);
FileTestHelper.assertFileExists(workDir, expiredForeign, true);
//create a file that is not a session file, it should be ignored
FileTestHelper.createFile("whatever.txt");
FileTestHelper.assertFileExists("whatever.txt", true);
FileTestHelper.createFile(workDir, "whatever.txt");
FileTestHelper.assertFileExists(workDir, "whatever.txt", true);
//create a file that is not a valid session filename, should be ignored
FileTestHelper.createFile("nonNumber_0.0.0.0_spuriousFile");
FileTestHelper.assertFileExists("nonNumber_0.0.0.0_spuriousFile", true);
FileTestHelper.createFile(workDir, "nonNumber_0.0.0.0_spuriousFile");
FileTestHelper.assertFileExists(workDir, "nonNumber_0.0.0.0_spuriousFile", true);
//create a file that is a non-expired session file for our context that should be ignored
String nonExpired = (System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)) + "_test_0.0.0.0_sessionb";
FileTestHelper.createFile(nonExpired);
FileTestHelper.assertFileExists(nonExpired, true);
FileTestHelper.createFile(workDir, nonExpired);
FileTestHelper.assertFileExists(workDir, nonExpired, true);
//create a file that is a never-expire session file for our context that should be ignored
String neverExpired = "0_test_0.0.0.0_sessionc";
FileTestHelper.createFile(neverExpired);
FileTestHelper.assertFileExists(neverExpired, true);
FileTestHelper.createFile(workDir, neverExpired);
FileTestHelper.assertFileExists(workDir, neverExpired, true);
//create a file that is a never-expire session file for another context that should be ignored
String foreignNeverExpired = "0_test_0.0.0.0_sessionc";
FileTestHelper.createFile(foreignNeverExpired);
FileTestHelper.assertFileExists(foreignNeverExpired, true);
FileTestHelper.createFile(workDir, foreignNeverExpired);
FileTestHelper.assertFileExists(workDir, foreignNeverExpired, true);
//walk all files in the store
((FileSessionDataStore)store).initializeStore();
//check results
FileTestHelper.assertSessionExists("sessiona", false);
FileTestHelper.assertFileExists("whatever.txt", true);
FileTestHelper.assertFileExists("nonNumber_0.0.0.0_spuriousFile", true);
FileTestHelper.assertFileExists(nonExpired, true);
FileTestHelper.assertFileExists(nonExpiredForeign, true);
FileTestHelper.assertFileExists(expiredForeign, true);
FileTestHelper.assertFileExists(neverExpired, true);
FileTestHelper.assertFileExists(foreignNeverExpired, true);
FileTestHelper.assertSessionExists(workDir, "sessiona", false);
FileTestHelper.assertFileExists(workDir, "whatever.txt", true);
FileTestHelper.assertFileExists(workDir, "nonNumber_0.0.0.0_spuriousFile", true);
FileTestHelper.assertFileExists(workDir, nonExpired, true);
FileTestHelper.assertFileExists(workDir, nonExpiredForeign, true);
FileTestHelper.assertFileExists(workDir, expiredForeign, true);
FileTestHelper.assertFileExists(workDir, neverExpired, true);
FileTestHelper.assertFileExists(workDir, foreignNeverExpired, true);
}
/**
@ -361,8 +352,8 @@ public class TestFileSessions extends AbstractTestBase
store.initialize(sessionContext);
String expectedFilename = (System.currentTimeMillis() + 10000) + "__test_0.0.0.0_validFile123";
FileTestHelper.createFile(expectedFilename);
FileTestHelper.assertFileExists(expectedFilename, true);
FileTestHelper.createFile(workDir, expectedFilename);
FileTestHelper.assertFileExists(workDir, expectedFilename, true);
store.start();
@ -376,7 +367,7 @@ public class TestFileSessions extends AbstractTestBase
//expected exception
}
FileTestHelper.assertFileExists(expectedFilename, false);
FileTestHelper.assertFileExists(workDir, expectedFilename, false);
}
/**
@ -403,22 +394,22 @@ public class TestFileSessions extends AbstractTestBase
//create a file for session abc that expired 5sec ago
long exp = now - 5000L;
String name1 = Long.toString(exp) + "__test_0.0.0.0_abc";
FileTestHelper.createFile(name1);
FileTestHelper.createFile(workDir, name1);
//create a file for same session that expired 4 sec ago
exp = now - 4000L;
String name2 = Long.toString(exp) + "__test_0.0.0.0_abc";
FileTestHelper.createFile(name2);
FileTestHelper.createFile(workDir, name2);
//make a file for same session that expired 3 sec ago
exp = now - 3000L;
String name3 = Long.toString(exp) + "__test_0.0.0.0_abc";
FileTestHelper.createFile(name3);
FileTestHelper.createFile(workDir, name3);
store.start();
FileTestHelper.assertFileExists(name1, false);
FileTestHelper.assertFileExists(name2, false);
FileTestHelper.assertFileExists(name3, true);
FileTestHelper.assertFileExists(workDir, name1, false);
FileTestHelper.assertFileExists(workDir, name2, false);
FileTestHelper.assertFileExists(workDir, name3, true);
}
}

View File

@ -19,27 +19,32 @@
package org.eclipse.jetty.server.session;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStoreFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* ClusteredOrphanedSessionTest
*/
@ExtendWith(WorkDirExtension.class)
public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessionTest
{
public static InfinispanTestSupport __testSupport;
public WorkDir workDir;
public InfinispanTestSupport testSupport;
@BeforeAll
public static void setup() throws Exception
@BeforeEach
public void setup() throws Exception
{
__testSupport = new InfinispanTestSupport();
__testSupport.setup();
testSupport = new InfinispanTestSupport();
testSupport.setup(workDir.getEmptyPathDir());
}
@AfterAll
public static void teardown() throws Exception
@AfterEach
public void teardown() throws Exception
{
__testSupport.teardown();
testSupport.teardown();
}
/**
@ -49,7 +54,7 @@ public class ClusteredOrphanedSessionTest extends AbstractClusteredOrphanedSessi
public SessionDataStoreFactory createSessionDataStoreFactory()
{
InfinispanSessionDataStoreFactory factory = new InfinispanSessionDataStoreFactory();
factory.setCache(__testSupport.getCache());
factory.setCache(testSupport.getCache());
return factory;
}
}

View File

@ -19,31 +19,36 @@
package org.eclipse.jetty.server.session;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStoreFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* ClusteredSerializedSessionScavengingTest
*/
@ExtendWith(WorkDirExtension.class)
public class ClusteredSerializedSessionScavengingTest extends AbstractClusteredSessionScavengingTest
{
public static InfinispanTestSupport __testSupport;
public WorkDir workDir;
public static InfinispanTestSupport testSupport;
@BeforeAll
public static void setup() throws Exception
@BeforeEach
public void setup() throws Exception
{
__testSupport = new InfinispanTestSupport();
__testSupport.setUseFileStore(true);
__testSupport.setSerializeSessionData(true);
__testSupport.setup();
testSupport = new InfinispanTestSupport();
testSupport.setUseFileStore(true);
testSupport.setSerializeSessionData(true);
testSupport.setup(workDir.getEmptyPathDir());
}
@AfterAll
public static void teardown() throws Exception
@AfterEach
public void teardown() throws Exception
{
if (__testSupport != null)
__testSupport.teardown();
if (testSupport != null)
testSupport.teardown();
}
@Override
@ -61,7 +66,7 @@ public class ClusteredSerializedSessionScavengingTest extends AbstractClusteredS
public SessionDataStoreFactory createSessionDataStoreFactory()
{
InfinispanSessionDataStoreFactory factory = new InfinispanSessionDataStoreFactory();
factory.setCache(__testSupport.getCache());
factory.setCache(testSupport.getCache());
return factory;
}
}

View File

@ -19,30 +19,35 @@
package org.eclipse.jetty.server.session;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStoreFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* ClusteredSessionScavengingTest
*/
@ExtendWith(WorkDirExtension.class)
public class ClusteredSessionScavengingTest extends AbstractClusteredSessionScavengingTest
{
public static InfinispanTestSupport __testSupport;
public WorkDir workDir;
public InfinispanTestSupport testSupport;
@BeforeAll
public static void setup() throws Exception
@BeforeEach
public void setup() throws Exception
{
__testSupport = new InfinispanTestSupport();
__testSupport.setUseFileStore(true);
__testSupport.setup();
testSupport = new InfinispanTestSupport();
testSupport.setUseFileStore(true);
testSupport.setup(workDir.getEmptyPathDir());
}
@AfterAll
public static void teardown() throws Exception
@AfterEach
public void teardown() throws Exception
{
if (__testSupport != null)
__testSupport.teardown();
if (testSupport != null)
testSupport.teardown();
}
@Override
@ -60,7 +65,7 @@ public class ClusteredSessionScavengingTest extends AbstractClusteredSessionScav
public SessionDataStoreFactory createSessionDataStoreFactory()
{
InfinispanSessionDataStoreFactory factory = new InfinispanSessionDataStoreFactory();
factory.setCache(__testSupport.getCache());
factory.setCache(testSupport.getCache());
return factory;
}
}

View File

@ -18,20 +18,26 @@
package org.eclipse.jetty.server.session;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
/**
* HotInitInfinispanSessionDataStoreTest
*/
@ExtendWith(WorkDirExtension.class)
public class InfinispanFileSessionDataStoreTest extends InfinispanSessionDataStoreTest
{
public WorkDir workDir;
@BeforeEach
public void setup() throws Exception
{
_testSupport = new InfinispanTestSupport();
_testSupport.setUseFileStore(true);
_testSupport.setup();
_testSupport.setup(workDir.getEmptyPathDir());
}
}

View File

@ -22,12 +22,15 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.session.infinispan.InfinispanSessionData;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStore;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStoreFactory;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.infinispan.query.Search;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -35,16 +38,19 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* InfinispanSessionDataStoreTest
*/
@ExtendWith(WorkDirExtension.class)
public class InfinispanSessionDataStoreTest extends AbstractSessionDataStoreTest
{
public InfinispanTestSupport _testSupport;
public WorkDir workDir;
@BeforeEach
public void setup() throws Exception
{
_testSupport = new InfinispanTestSupport();
_testSupport.setup();
_testSupport.setup(workDir.getEmptyPathDir());
}
@AfterEach

View File

@ -45,10 +45,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* InfinispanTestSupport
*/
@ExtendWith(WorkDirExtension.class)
public class InfinispanTestSupport
{
public WorkDir workDir;
public static final String DEFAULT_CACHE_NAME = "session_test_cache";
public Cache _cache;
@ -100,9 +98,8 @@ public class InfinispanTestSupport
return _cache;
}
public void setup() throws Exception
public void setup(Path root) throws Exception
{
Path root = workDir.getEmptyPathDir();
Path indexesDir = root.resolve("indexes");
FS.ensureDirExists(indexesDir);

View File

@ -22,12 +22,15 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.session.infinispan.InfinispanSessionData;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStore;
import org.eclipse.jetty.session.infinispan.InfinispanSessionDataStoreFactory;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.infinispan.query.Search;
import org.infinispan.query.dsl.Query;
import org.infinispan.query.dsl.QueryFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@ -35,17 +38,20 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* SerializedInfinispanSessionDataStoreTest
*/
@ExtendWith(WorkDirExtension.class)
public class SerializedInfinispanSessionDataStoreTest extends AbstractSessionDataStoreTest
{
public InfinispanTestSupport _testSupport;
public WorkDir workDir;
@BeforeEach
public void setup() throws Exception
{
_testSupport = new InfinispanTestSupport();
_testSupport.setSerializeSessionData(true);
_testSupport.setup();
_testSupport.setup(workDir.getEmptyPathDir());
}
@AfterEach