FileSessionStorage implements SessionStorage { @Override public void persistSession(final HttpSessionImpl session) throws IOException { if (!isSessionIdValid(session.getId())) { throw new IllegalArgumentException("Session ID can not be empty and must be composed of 32 characters"); } File file = new File(getSessionStoragePath(session.getId())); if (!file.exists() && !file.createNewFile()) { throw new IOException("Unable to create new file " + file.getAbsolutePath()); } writeSession(session, file); LOGGER.log(Level.FINE, "Persisted session {0} in {1}", new Object[]{session.getId(), tempPath}); } FileSessionStorage(final String tempPath); @Override void persistSession(final HttpSessionImpl session); @Override HttpSessionImpl getSession(final String id); @Override boolean removeSession(final HttpSessionImpl session);  }
@Test(expected = IllegalArgumentException.class) public void shouldValidateSessionNameLength() throws IOException { HttpSessionImpl sessionWrapper = new HttpSessionImpl("abcX8", System.currentTimeMillis()); fileSessionStorage.persistSession(sessionWrapper); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateSessionNameNull() throws IOException { HttpSessionImpl sessionWrapper = new HttpSessionImpl(null, System.currentTimeMillis()); fileSessionStorage.persistSession(sessionWrapper); }
@Test(expected = IllegalArgumentException.class) public void shouldValidateSessionNameIllegalCharacters() throws IOException { HttpSessionImpl sessionWrapper = new HttpSessionImpl(ILLEGAL_SESSION_ID, System.currentTimeMillis()); fileSessionStorage.persistSession(sessionWrapper); }
@Test(expected = IOException.class) public void shouldThrowExceptionWhenUnableToCreateSessionDirectory() throws IOException { assumeFalse(OsUtils.isWindows()); String nonWritableDirectory = FileUtils.createTempDirectory(); new File(nonWritableDirectory).setWritable(false); FileSessionStorage storage = new FileSessionStorage(nonWritableDirectory); HttpSessionImpl sessionWrapper = new HttpSessionImpl(VALID_SESSION_ID, System.currentTimeMillis()); sessionWrapper.setAttribute("attributeName", "SomeValue"); storage.persistSession(sessionWrapper); }
@Test(expected = IOException.class) public void shouldThrowExceptionWhenUnableToCreateFile() throws IOException { String nonExistentDirectory = "/tmp/nonexistent-" + Math.random() + "/"; assertThat(new File(nonExistentDirectory).exists(), is(false)); SessionStorage sessionStorage = new FileSessionStorage(nonExistentDirectory); sessionStorage.persistSession(new HttpSessionImpl(VALID_SESSION_ID, System.currentTimeMillis())); }