org.springframework.session.MapSession Java Examples

The following examples show how to use org.springframework.session.MapSession. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 7 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void getSessionFound() {
	Session saved = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	saved.setAttribute("savedName", "savedValue");
	given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class))).willReturn(Collections.singletonList(saved));

	JdbcSession session = this.repository.findById(saved.getId());

	assertThat(session.getId()).isEqualTo(saved.getId());
	assertThat(session.isNew()).isFalse();
	assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
	verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class),
			isA(ResultSetExtractor.class));
}
 
Example #2
Source File: RedisIndexedSessionRepository.java    From spring-session with Apache License 2.0 6 votes vote down vote up
RedisSession(MapSession cached, boolean isNew) {
	this.cached = cached;
	this.isNew = isNew;
	this.originalSessionId = cached.getId();
	Map<String, String> indexes = RedisIndexedSessionRepository.this.indexResolver.resolveIndexesFor(this);
	this.originalPrincipalName = indexes.get(PRINCIPAL_NAME_INDEX_NAME);
	if (this.isNew) {
		this.delta.put(RedisSessionMapper.CREATION_TIME_KEY, cached.getCreationTime().toEpochMilli());
		this.delta.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY,
				(int) cached.getMaxInactiveInterval().getSeconds());
		this.delta.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, cached.getLastAccessedTime().toEpochMilli());
	}
	if (this.isNew || (RedisIndexedSessionRepository.this.saveMode == SaveMode.ALWAYS)) {
		getAttributeNames().forEach((attributeName) -> this.delta.put(getSessionAttrNameKey(attributeName),
				cached.getAttribute(attributeName)));
	}
}
 
Example #3
Source File: SessionRepositoryFilterTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test // gh-1229
void doFilterAdapterGetRequestedSessionIdForInvalidSession() throws Exception {
	SessionRepository<MapSession> sessionRepository = new MapSessionRepository(new HashMap<>());

	this.filter = new SessionRepositoryFilter<>(sessionRepository);
	this.filter.setHttpSessionIdResolver(this.strategy);
	final String expectedId = "HttpSessionIdResolver-requested-id1";
	final String otherId = "HttpSessionIdResolver-requested-id2";

	given(this.strategy.resolveSessionIds(any(HttpServletRequest.class)))
			.willReturn(Arrays.asList(expectedId, otherId));

	doFilter(new DoInFilter() {
		@Override
		public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) {
			assertThat(wrappedRequest.getRequestedSessionId()).isEqualTo(expectedId);
			assertThat(wrappedRequest.isRequestedSessionIdValid()).isFalse();
		}
	});
}
 
Example #4
Source File: SessionRepositoryFilterTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void doFilterAdapterGetRequestedSessionId() throws Exception {
	SessionRepository<MapSession> sessionRepository = spy(new MapSessionRepository(new ConcurrentHashMap<>()));

	this.filter = new SessionRepositoryFilter<>(sessionRepository);
	this.filter.setHttpSessionIdResolver(this.strategy);
	final String expectedId = "HttpSessionIdResolver-requested-id";

	given(this.strategy.resolveSessionIds(any(HttpServletRequest.class)))
			.willReturn(Collections.singletonList(expectedId));
	given(sessionRepository.findById(anyString())).willReturn(new MapSession(expectedId));

	doFilter(new DoInFilter() {
		@Override
		public void doFilter(HttpServletRequest wrappedRequest, HttpServletResponse wrappedResponse) {
			String actualId = wrappedRequest.getRequestedSessionId();
			assertThat(actualId).isEqualTo(expectedId);
		}
	});
}
 
Example #5
Source File: FixedMapSessionRepository.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 6 votes vote down vote up
@Override
public ExpiringSession getSession(final String id)
{
	final ExpiringSession saved = sessions.get(id);
	if (saved == null)
	{
		return null;
	}
	if (saved.isExpired())
	{
		final boolean expired = true;
		deleteAndFireEvent(saved.getId(), expired);
		return null;
	}

	return new MapSession(saved);
}
 
Example #6
Source File: ReactiveRedisSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void saveWithSaveModeOnGetAttribute() {
	given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
	given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
	given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
	given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
	this.repository.setSaveMode(SaveMode.ON_GET_ATTRIBUTE);
	MapSession delegate = new MapSession();
	delegate.setAttribute("attribute1", "value1");
	delegate.setAttribute("attribute2", "value2");
	delegate.setAttribute("attribute3", "value3");
	RedisSession session = this.repository.new RedisSession(delegate, false);
	session.getAttribute("attribute2");
	session.setAttribute("attribute3", "value4");
	StepVerifier.create(this.repository.save(session)).verifyComplete();
	verify(this.redisOperations).hasKey(anyString());
	verify(this.redisOperations).opsForHash();
	verify(this.hashOperations).putAll(anyString(), this.delta.capture());
	assertThat(this.delta.getValue()).hasSize(2);
	verify(this.redisOperations).expire(anyString(), any());
	verifyZeroInteractions(this.redisOperations);
	verifyZeroInteractions(this.hashOperations);
}
 
Example #7
Source File: RedisSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void findById_SessionExists_ShouldReturnSession() {
	Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
	given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
			.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
					RedisSessionMapper.LAST_ACCESSED_TIME_KEY, now.toEpochMilli(),
					RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
					RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
	RedisSession session = this.sessionRepository.findById(TEST_SESSION_ID);
	assertThat(session.getId()).isEqualTo(TEST_SESSION_ID);
	assertThat(session.getCreationTime()).isEqualTo(Instant.EPOCH);
	assertThat(session.getLastAccessedTime()).isEqualTo(now);
	assertThat(session.getMaxInactiveInterval())
			.isEqualTo(Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS));
	assertThat(session.getAttributeNames()).isEqualTo(Collections.singleton("attribute1"));
	assertThat(session.<String>getAttribute("attribute1")).isEqualTo("value1");
	verify(this.sessionRedisOperations).opsForHash();
	verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY));
	verifyNoMoreInteractions(this.sessionRedisOperations);
	verifyNoMoreInteractions(this.sessionHashOperations);
}
 
Example #8
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void onMessageCreatedInOtherDatabase() {
	JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
	this.redisRepository.setApplicationEventPublisher(this.publisher);
	this.redisRepository.setDefaultSerializer(serializer);

	MapSession session = this.cached;
	String channel = "spring:session:event:created:1:" + session.getId();
	byte[] body = serializer.serialize(new HashMap());
	DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body);

	this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8));

	assertThat(this.event.getAllValues()).isEmpty();
	verifyZeroInteractions(this.publisher);
}
 
Example #9
Source File: RedissonSessionRepository.java    From redisson with Apache License 2.0 6 votes vote down vote up
private MapSession loadSession(String sessionId) {
    RMap<String, Object> map = redisson.getMap(keyPrefix + sessionId, new CompositeCodec(StringCodec.INSTANCE, redisson.getConfig().getCodec()));
    Set<Entry<String, Object>> entrySet = map.readAllEntrySet();
    if (entrySet.isEmpty()) {
        return null;
    }
    
    MapSession delegate = new MapSession(sessionId);
    for (Entry<String, Object> entry : entrySet) {
        if ("session:creationTime".equals(entry.getKey())) {
            delegate.setCreationTime(Instant.ofEpochMilli((Long) entry.getValue()));
        } else if ("session:lastAccessedTime".equals(entry.getKey())) {
            delegate.setLastAccessedTime(Instant.ofEpochMilli((Long) entry.getValue()));
        } else if ("session:maxInactiveInterval".equals(entry.getKey())) {
            delegate.setMaxInactiveInterval(Duration.ofSeconds((Long) entry.getValue()));
        } else if (entry.getKey().startsWith(SESSION_ATTR_PREFIX)) {
            delegate.setAttribute(entry.getKey().substring(SESSION_ATTR_PREFIX.length()), entry.getValue());
        }
    }
    return delegate;
}
 
Example #10
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test // gh-309
void onMessageCreatedCustomSerializer() {
	MapSession session = this.cached;
	byte[] pattern = "".getBytes(StandardCharsets.UTF_8);
	byte[] body = new byte[0];
	String channel = "spring:session:event:0:created:" + session.getId();
	given(this.defaultSerializer.deserialize(body)).willReturn(new HashMap<String, Object>());
	DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8), body);
	this.redisRepository.setApplicationEventPublisher(this.publisher);

	this.redisRepository.onMessage(message, pattern);

	verify(this.publisher).publishEvent(this.event.capture());
	assertThat(this.event.getValue().getSessionId()).isEqualTo(session.getId());
	verify(this.defaultSerializer).deserialize(body);
}
 
Example #11
Source File: ReactiveRedisSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void saveWithSaveModeOnSetAttribute() {
	given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
	given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
	given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
	given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));
	this.repository.setSaveMode(SaveMode.ON_SET_ATTRIBUTE);
	MapSession delegate = new MapSession();
	delegate.setAttribute("attribute1", "value1");
	delegate.setAttribute("attribute2", "value2");
	delegate.setAttribute("attribute3", "value3");
	RedisSession session = this.repository.new RedisSession(delegate, false);
	session.getAttribute("attribute2");
	session.setAttribute("attribute3", "value4");
	StepVerifier.create(this.repository.save(session)).verifyComplete();
	verify(this.redisOperations).hasKey(anyString());
	verify(this.redisOperations).opsForHash();
	verify(this.hashOperations).putAll(anyString(), this.delta.capture());
	assertThat(this.delta.getValue()).hasSize(1);
	verify(this.redisOperations).expire(anyString(), any());
	verifyZeroInteractions(this.redisOperations);
	verifyZeroInteractions(this.hashOperations);
}
 
Example #12
Source File: RedisSessionMapperTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void apply_ValidMap_ShouldReturnSession() {
	Map<String, Object> sessionMap = new HashMap<>();
	sessionMap.put(RedisSessionMapper.CREATION_TIME_KEY, 0L);
	sessionMap.put(RedisSessionMapper.LAST_ACCESSED_TIME_KEY, 0L);
	sessionMap.put(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, 1800);
	sessionMap.put(RedisSessionMapper.ATTRIBUTE_PREFIX + "existing", "value");
	sessionMap.put(RedisSessionMapper.ATTRIBUTE_PREFIX + "missing", null);
	MapSession session = this.mapper.apply(sessionMap);
	assertThat(session.getId()).isEqualTo("id");
	assertThat(session.getCreationTime()).isEqualTo(Instant.ofEpochMilli(0));
	assertThat(session.getLastAccessedTime()).isEqualTo(Instant.ofEpochMilli(0));
	assertThat(session.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(30));
	assertThat(session.getAttributeNames()).hasSize(1);
	assertThat((String) session.getAttribute("existing")).isEqualTo("value");
}
 
Example #13
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void onMessageExpiredInOtherDatabase() {
	JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
	this.redisRepository.setApplicationEventPublisher(this.publisher);
	this.redisRepository.setDefaultSerializer(serializer);

	MapSession session = this.cached;
	String channel = "__keyevent@1__:expired";
	String body = "spring:session:sessions:expires:" + session.getId();
	DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
			body.getBytes(StandardCharsets.UTF_8));

	this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8));

	assertThat(this.event.getAllValues()).isEmpty();
	verifyZeroInteractions(this.publisher);
}
 
Example #14
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void onMessageDeletedInOtherDatabase() {
	JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
	this.redisRepository.setApplicationEventPublisher(this.publisher);
	this.redisRepository.setDefaultSerializer(serializer);

	MapSession session = this.cached;
	String channel = "__keyevent@1__:del";
	String body = "spring:session:sessions:expires:" + session.getId();
	DefaultMessage message = new DefaultMessage(channel.getBytes(StandardCharsets.UTF_8),
			body.getBytes(StandardCharsets.UTF_8));

	this.redisRepository.onMessage(message, "".getBytes(StandardCharsets.UTF_8));

	assertThat(this.event.getAllValues()).isEmpty();
	verifyZeroInteractions(this.publisher);
}
 
Example #15
Source File: JdbcIndexedSessionRepository.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Override
public List<JdbcSession> extractData(ResultSet rs) throws SQLException, DataAccessException {
	List<JdbcSession> sessions = new ArrayList<>();
	while (rs.next()) {
		String id = rs.getString("SESSION_ID");
		JdbcSession session;
		if (sessions.size() > 0 && getLast(sessions).getId().equals(id)) {
			session = getLast(sessions);
		}
		else {
			MapSession delegate = new MapSession(id);
			String primaryKey = rs.getString("PRIMARY_ID");
			delegate.setCreationTime(Instant.ofEpochMilli(rs.getLong("CREATION_TIME")));
			delegate.setLastAccessedTime(Instant.ofEpochMilli(rs.getLong("LAST_ACCESS_TIME")));
			delegate.setMaxInactiveInterval(Duration.ofSeconds(rs.getInt("MAX_INACTIVE_INTERVAL")));
			session = new JdbcSession(delegate, primaryKey, false);
		}
		String attributeName = rs.getString("ATTRIBUTE_NAME");
		if (attributeName != null) {
			byte[] bytes = getLobHandler().getBlobAsBytes(rs, "ATTRIBUTE_BYTES");
			session.delegate.setAttribute(attributeName, lazily(() -> deserialize(bytes)));
		}
		sessions.add(session);
	}
	return sessions;
}
 
Example #16
Source File: AbstractJdbcIndexedSessionRepositoryITests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void findByPrincipalNameExpireRemovesIndex() {
	String principalName = "findByPrincipalNameExpireRemovesIndex" + UUID.randomUUID();
	JdbcSession toSave = this.repository.createSession();
	toSave.setAttribute(INDEX_NAME, principalName);
	toSave.setLastAccessedTime(Instant.now().minusSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));

	this.repository.save(toSave);
	this.repository.cleanUpExpiredSessions();

	Map<String, JdbcSession> findByPrincipalName = this.repository.findByIndexNameAndIndexValue(INDEX_NAME,
			principalName);

	assertThat(findByPrincipalName).hasSize(0);
	assertThat(findByPrincipalName.keySet()).doesNotContain(toSave.getId());
}
 
Example #17
Source File: AbstractJdbcIndexedSessionRepositoryITests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test // gh-1133
void sessionFromStoreResolvesAttributesLazily() {
	JdbcSession session = this.repository.createSession();
	session.setAttribute("attribute1", "value1");
	session.setAttribute("attribute2", "value2");
	this.repository.save(session);
	session = this.repository.findById(session.getId());
	MapSession delegate = (MapSession) ReflectionTestUtils.getField(session, "delegate");

	Supplier attribute1 = delegate.getAttribute("attribute1");
	assertThat(ReflectionTestUtils.getField(attribute1, "value")).isNull();
	assertThat((String) session.getAttribute("attribute1")).isEqualTo("value1");
	assertThat(ReflectionTestUtils.getField(attribute1, "value")).isEqualTo("value1");
	Supplier attribute2 = delegate.getAttribute("attribute2");
	assertThat(ReflectionTestUtils.getField(attribute2, "value")).isNull();
	assertThat((String) session.getAttribute("attribute2")).isEqualTo("value2");
	assertThat(ReflectionTestUtils.getField(attribute2, "value")).isEqualTo("value2");
}
 
Example #18
Source File: ReactiveRedisSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void saveRemoveAttribute() {
	given(this.redisOperations.hasKey(anyString())).willReturn(Mono.just(true));
	given(this.redisOperations.opsForHash()).willReturn(this.hashOperations);
	given(this.hashOperations.putAll(anyString(), any())).willReturn(Mono.just(true));
	given(this.redisOperations.expire(anyString(), any())).willReturn(Mono.just(true));

	String attrName = "attrName";
	RedisSession session = this.repository.new RedisSession(new MapSession(), false);
	session.removeAttribute(attrName);
	StepVerifier.create(this.repository.save(session)).verifyComplete();

	verify(this.redisOperations).hasKey(anyString());
	verify(this.redisOperations).opsForHash();
	verify(this.hashOperations).putAll(anyString(), this.delta.capture());
	verify(this.redisOperations).expire(anyString(), any());
	verifyZeroInteractions(this.redisOperations);
	verifyZeroInteractions(this.hashOperations);

	assertThat(this.delta.getAllValues().get(0))
			.isEqualTo(map(RedisIndexedSessionRepository.getSessionAttrNameKey(attrName), null));
}
 
Example #19
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void flushModeImmediateCreate() {
	given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
	given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);

	this.redisRepository.setFlushMode(FlushMode.IMMEDIATE);
	RedisSession session = this.redisRepository.createSession();

	Map<String, Object> delta = getDelta();
	assertThat(delta.size()).isEqualTo(3);
	Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY);
	assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
	assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
			.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
	assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
			.isEqualTo(session.getCreationTime().toEpochMilli());
}
 
Example #20
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void saveWithSaveModeOnSetAttribute() {
	given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
	given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);
	this.redisRepository.setSaveMode(SaveMode.ON_SET_ATTRIBUTE);
	MapSession delegate = new MapSession();
	delegate.setAttribute("attribute1", "value1");
	delegate.setAttribute("attribute2", "value2");
	delegate.setAttribute("attribute3", "value3");
	RedisSession session = this.redisRepository.new RedisSession(delegate, false);
	session.getAttribute("attribute2");
	session.setAttribute("attribute3", "value4");
	this.redisRepository.save(session);
	assertThat(getDelta()).hasSize(1);
}
 
Example #21
Source File: HazelcastIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void saveWithSaveModeOnGetAttribute() {
	verify(this.sessions).addEntryListener(any(MapListener.class), anyBoolean());
	this.repository.setSaveMode(SaveMode.ON_GET_ATTRIBUTE);
	MapSession delegate = new MapSession();
	delegate.setAttribute("attribute1", "value1");
	delegate.setAttribute("attribute2", "value2");
	delegate.setAttribute("attribute3", "value3");
	HazelcastSession session = this.repository.new HazelcastSession(delegate, false);
	session.getAttribute("attribute2");
	session.setAttribute("attribute3", "value4");
	this.repository.save(session);
	ArgumentCaptor<SessionUpdateEntryProcessor> captor = ArgumentCaptor.forClass(SessionUpdateEntryProcessor.class);
	verify(this.sessions).executeOnKey(eq(session.getId()), captor.capture());
	assertThat((Map<String, Object>) ReflectionTestUtils.getField(captor.getValue(), "delta")).hasSize(2);
	verifyZeroInteractions(this.sessions);
}
 
Example #22
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
void saveNewSession() {
	RedisSession session = this.redisRepository.createSession();
	given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
	given(this.redisOperations.boundValueOps(anyString())).willReturn(this.boundValueOperations);

	this.redisRepository.save(session);

	Map<String, Object> delta = getDelta();
	assertThat(delta.size()).isEqualTo(3);
	Object creationTime = delta.get(RedisSessionMapper.CREATION_TIME_KEY);
	assertThat(creationTime).isEqualTo(session.getCreationTime().toEpochMilli());
	assertThat(delta.get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY))
			.isEqualTo((int) Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS).getSeconds());
	assertThat(delta.get(RedisSessionMapper.LAST_ACCESSED_TIME_KEY))
			.isEqualTo(session.getCreationTime().toEpochMilli());
}
 
Example #23
Source File: RedisIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void delete() {
	String attrName = "attrName";
	MapSession expected = new MapSession();
	expected.setLastAccessedTime(Instant.now().minusSeconds(60));
	expected.setAttribute(attrName, "attrValue");
	given(this.redisOperations.boundHashOps(anyString())).willReturn(this.boundHashOperations);
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);
	Map map = map(RedisIndexedSessionRepository.getSessionAttrNameKey(attrName), expected.getAttribute(attrName),
			RedisSessionMapper.CREATION_TIME_KEY, expected.getCreationTime().toEpochMilli(),
			RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, (int) expected.getMaxInactiveInterval().getSeconds(),
			RedisSessionMapper.LAST_ACCESSED_TIME_KEY, expected.getLastAccessedTime().toEpochMilli());
	given(this.boundHashOperations.entries()).willReturn(map);
	given(this.redisOperations.boundSetOps(anyString())).willReturn(this.boundSetOperations);

	String id = expected.getId();
	this.redisRepository.deleteById(id);

	assertThat(getDelta().get(RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY)).isEqualTo(0);
	verify(this.redisOperations, atLeastOnce()).delete(getKey("expires:" + id));
	verify(this.redisOperations, never()).boundValueOps(getKey("expires:" + id));
}
 
Example #24
Source File: RedisIndexedSessionRepository.java    From spring-session with Apache License 2.0 6 votes vote down vote up
private MapSession loadSession(String id, Map<Object, Object> entries) {
	MapSession loaded = new MapSession(id);
	for (Map.Entry<Object, Object> entry : entries.entrySet()) {
		String key = (String) entry.getKey();
		if (RedisSessionMapper.CREATION_TIME_KEY.equals(key)) {
			loaded.setCreationTime(Instant.ofEpochMilli((long) entry.getValue()));
		}
		else if (RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY.equals(key)) {
			loaded.setMaxInactiveInterval(Duration.ofSeconds((int) entry.getValue()));
		}
		else if (RedisSessionMapper.LAST_ACCESSED_TIME_KEY.equals(key)) {
			loaded.setLastAccessedTime(Instant.ofEpochMilli((long) entry.getValue()));
		}
		else if (key.startsWith(RedisSessionMapper.ATTRIBUTE_PREFIX)) {
			loaded.setAttribute(key.substring(RedisSessionMapper.ATTRIBUTE_PREFIX.length()), entry.getValue());
		}
	}
	return loaded;
}
 
Example #25
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void saveUpdatedRemoveSingleAttribute() {
	JdbcSession session = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	session.setAttribute("testName", "testValue");
	session.clearChangeFlags();
	session.removeAttribute("testName");

	this.repository.save(session);

	assertThat(session.isNew()).isFalse();
	verify(this.jdbcOperations, times(1)).update(startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"),
			isA(PreparedStatementSetter.class));
	verifyNoMoreInteractions(this.jdbcOperations);
}
 
Example #26
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test // gh-1070
void saveUpdatedModifyAndRemoveAttribute() {
	JdbcSession session = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	session.setAttribute("testName", "testValue1");
	session.clearChangeFlags();
	session.setAttribute("testName", "testValue2");
	session.removeAttribute("testName");

	this.repository.save(session);

	assertThat(session.isNew()).isFalse();
	verify(this.jdbcOperations).update(startsWith("DELETE FROM SPRING_SESSION_ATTRIBUTES WHERE"),
			isA(PreparedStatementSetter.class));
	verifyNoMoreInteractions(this.jdbcOperations);
}
 
Example #27
Source File: RedisSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
void findById_SessionExistsAndIsExpired_ShouldReturnNull() {
	given(this.sessionHashOperations.entries(eq(TEST_SESSION_KEY)))
			.willReturn(mapOf(RedisSessionMapper.CREATION_TIME_KEY, Instant.EPOCH.toEpochMilli(),
					RedisSessionMapper.LAST_ACCESSED_TIME_KEY, Instant.EPOCH.toEpochMilli(),
					RedisSessionMapper.MAX_INACTIVE_INTERVAL_KEY, MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS,
					RedisSessionMapper.ATTRIBUTE_PREFIX + "attribute1", "value1"));
	assertThat(this.sessionRepository.findById(TEST_SESSION_ID)).isNull();
	verify(this.sessionRedisOperations).opsForHash();
	verify(this.sessionHashOperations).entries(eq(TEST_SESSION_KEY));
	verify(this.sessionRedisOperations).delete(eq(TEST_SESSION_KEY));
	verifyNoMoreInteractions(this.sessionRedisOperations);
	verifyNoMoreInteractions(this.sessionHashOperations);
}
 
Example #28
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void saveUpdatedLastAccessedTime() {
	JdbcSession session = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	session.setLastAccessedTime(Instant.now());

	this.repository.save(session);

	assertThat(session.isNew()).isFalse();
	verify(this.jdbcOperations, times(1)).update(startsWith("UPDATE SPRING_SESSION SET"),
			isA(PreparedStatementSetter.class));
	verifyNoMoreInteractions(this.jdbcOperations);
}
 
Example #29
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test
void saveUnchanged() {
	JdbcSession session = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);

	this.repository.save(session);

	assertThat(session.isNew()).isFalse();
	verifyNoMoreInteractions(this.jdbcOperations);
}
 
Example #30
Source File: JdbcIndexedSessionRepositoryTests.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Test // gh-1070
void saveUpdatedAddAndModifyAttribute() {
	JdbcSession session = this.repository.new JdbcSession(new MapSession(), "primaryKey", false);
	session.setAttribute("testName", "testValue1");
	session.setAttribute("testName", "testValue2");

	this.repository.save(session);

	assertThat(session.isNew()).isFalse();
	verify(this.jdbcOperations).update(startsWith("INSERT INTO SPRING_SESSION_ATTRIBUTES("),
			isA(PreparedStatementSetter.class));
	verifyNoMoreInteractions(this.jdbcOperations);
}