Java Code Examples for org.springframework.session.MapSession

The following examples show how to use org.springframework.session.MapSession. These examples are extracted from open source projects. 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
@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 2
@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 3
@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 4
@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 5
Source Project: redisson   Source File: RedissonSessionRepository.java    License: 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 6
@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 7
@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 8
@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 9
@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 10
Source Project: spring-session   Source File: RedisSessionMapperTests.java    License: 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 11
@Test
void onMessageExpiredInOtherDatabase() {
	JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
	this.redisRepository.setApplicationEventPublisher(this.publisher);
	this.redisRepository.setDefaultSerializer(serializer);

	MapSession session = this.cached;
	String channel = "[email protected]__: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 12
@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 13
@Test
void onMessageDeletedInOtherDatabase() {
	JdkSerializationRedisSerializer serializer = new JdkSerializationRedisSerializer();
	this.redisRepository.setApplicationEventPublisher(this.publisher);
	this.redisRepository.setDefaultSerializer(serializer);

	MapSession session = this.cached;
	String channel = "[email protected]__: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 14
@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 15
@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
@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
@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
@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
@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 20
@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 21
@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 22
@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
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 24
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 25
Source Project: redisson   Source File: RedissonSessionRepository.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RedissonSession findById(String id) {
    MapSession mapSession = loadSession(id);
    if (mapSession == null || mapSession.isExpired()) {
        return null;
    }
    return new RedissonSession(mapSession);
}
 
Example 26
Source Project: spring-session   Source File: IndexDocTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void repositoryDemo() {
	RepositoryDemo<MapSession> demo = new RepositoryDemo<>();
	demo.repository = new MapSessionRepository(new ConcurrentHashMap<>());

	demo.demo();
}
 
Example 27
@Test
void springSessionDestroyedTranslatedToSpringSecurityDestroyed() {
	Session session = new MapSession();

	this.publisher.publishEvent(new org.springframework.session.events.SessionDestroyedEvent(this, session));

	assertThat(this.listener.getEvent().getId()).isEqualTo(session.getId());
}
 
Example 28
Source Project: spring-session   Source File: Initializer.java    License: Apache License 2.0 5 votes vote down vote up
private HazelcastInstance createHazelcastInstance() {
	Config config = new Config();
	NetworkConfig networkConfig = config.getNetworkConfig();
	networkConfig.setPort(0);
	networkConfig.getJoin().getMulticastConfig().setEnabled(false);
	config.getMapConfig(SESSION_MAP_NAME).setTimeToLiveSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS);
	return Hazelcast.newHazelcastInstance(config);
}
 
Example 29
@BeforeEach
void setup() {
	MockitoAnnotations.initMocks(this);
	String sessionId = "session-id";
	MapSession session = new MapSession(sessionId);

	this.attributes = new HashMap<>();
	SessionRepositoryMessageInterceptor.setSessionId(this.attributes, sessionId);

	given(this.wsSession.getAttributes()).willReturn(this.attributes);
	given(this.wsSession.getPrincipal()).willReturn(this.principal);
	given(this.wsSession.getId()).willReturn("wsSession-id");

	given(this.wsSession2.getAttributes()).willReturn(this.attributes);
	given(this.wsSession2.getPrincipal()).willReturn(this.principal);
	given(this.wsSession2.getId()).willReturn("wsSession-id2");

	Map<String, Object> headers = new HashMap<>();
	headers.put(SimpMessageHeaderAccessor.SESSION_ATTRIBUTES, this.attributes);
	given(this.message.getHeaders()).willReturn(new MessageHeaders(headers));

	this.listener = new WebSocketRegistryListener();
	this.connect = new SessionConnectEvent(this.listener, this.wsSession);
	this.connect2 = new SessionConnectEvent(this.listener, this.wsSession2);
	this.disconnect = new SessionDisconnectEvent(this.listener, this.message, this.wsSession.getId(),
			CloseStatus.NORMAL);
	this.deleted = new SessionDeletedEvent(this.listener, session);
	this.expired = new SessionExpiredEvent(this.listener, session);
}
 
Example 30
@BeforeEach
void setup() {
	MockitoAnnotations.initMocks(this);
	this.listener = new SessionEventHttpSessionListenerAdapter(Arrays.asList(this.listener1, this.listener2));
	this.listener.setServletContext(new MockServletContext());

	Session session = new MapSession();
	this.destroyed = new SessionDestroyedEvent(this, session);
	this.created = new SessionCreatedEvent(this, session);
}