Search in sources :

Example 11 with Session

use of org.springframework.session.Session in project spring-session by spring-projects.

the class JdbcOperationsSessionRepository method save.

@Override
public void save(final JdbcSession session) {
    if (session.isNew()) {
        this.transactionOperations.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.createSessionQuery, ps -> {
                    ps.setString(1, session.primaryKey);
                    ps.setString(2, session.getId());
                    ps.setLong(3, session.getCreationTime().toEpochMilli());
                    ps.setLong(4, session.getLastAccessedTime().toEpochMilli());
                    ps.setInt(5, (int) session.getMaxInactiveInterval().getSeconds());
                    ps.setLong(6, session.getExpiryTime().toEpochMilli());
                    ps.setString(7, session.getPrincipalName());
                });
                if (!session.getAttributeNames().isEmpty()) {
                    final List<String> attributeNames = new ArrayList<>(session.getAttributeNames());
                    JdbcOperationsSessionRepository.this.jdbcOperations.batchUpdate(JdbcOperationsSessionRepository.this.createSessionAttributeQuery, new BatchPreparedStatementSetter() {

                        @Override
                        public void setValues(PreparedStatement ps, int i) throws SQLException {
                            String attributeName = attributeNames.get(i);
                            ps.setString(1, session.primaryKey);
                            ps.setString(2, attributeName);
                            serialize(ps, 3, session.getAttribute(attributeName));
                        }

                        @Override
                        public int getBatchSize() {
                            return attributeNames.size();
                        }
                    });
                }
            }
        });
    } else {
        this.transactionOperations.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                if (session.isChanged()) {
                    JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.updateSessionQuery, ps -> {
                        ps.setString(1, session.getId());
                        ps.setLong(2, session.getLastAccessedTime().toEpochMilli());
                        ps.setInt(3, (int) session.getMaxInactiveInterval().getSeconds());
                        ps.setLong(4, session.getExpiryTime().toEpochMilli());
                        ps.setString(5, session.getPrincipalName());
                        ps.setString(6, session.primaryKey);
                    });
                }
                Map<String, Object> delta = session.getDelta();
                if (!delta.isEmpty()) {
                    for (final Map.Entry<String, Object> entry : delta.entrySet()) {
                        if (entry.getValue() == null) {
                            JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.deleteSessionAttributeQuery, ps -> {
                                ps.setString(1, session.primaryKey);
                                ps.setString(2, entry.getKey());
                            });
                        } else {
                            int updatedCount = JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.updateSessionAttributeQuery, ps -> {
                                serialize(ps, 1, entry.getValue());
                                ps.setString(2, session.primaryKey);
                                ps.setString(3, entry.getKey());
                            });
                            if (updatedCount == 0) {
                                JdbcOperationsSessionRepository.this.jdbcOperations.update(JdbcOperationsSessionRepository.this.createSessionAttributeQuery, ps -> {
                                    ps.setString(1, session.primaryKey);
                                    ps.setString(2, entry.getKey());
                                    serialize(ps, 3, entry.getValue());
                                });
                            }
                        }
                    }
                }
            }
        });
    }
    session.clearChangeFlags();
}
Also used : BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) DataAccessException(org.springframework.dao.DataAccessException) JdbcOperations(org.springframework.jdbc.core.JdbcOperations) TransactionDefinition(org.springframework.transaction.TransactionDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) LobHandler(org.springframework.jdbc.support.lob.LobHandler) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) TypeDescriptor(org.springframework.core.convert.TypeDescriptor) Duration(java.time.Duration) Map(java.util.Map) DeserializingConverter(org.springframework.core.serializer.support.DeserializingConverter) DefaultLobHandler(org.springframework.jdbc.support.lob.DefaultLobHandler) FindByIndexNameSessionRepository(org.springframework.session.FindByIndexNameSessionRepository) ConversionService(org.springframework.core.convert.ConversionService) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) Set(java.util.Set) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) Session(org.springframework.session.Session) UUID(java.util.UUID) PreparedStatement(java.sql.PreparedStatement) Instant(java.time.Instant) SerializingConverter(org.springframework.core.serializer.support.SerializingConverter) List(java.util.List) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionOperations(org.springframework.transaction.support.TransactionOperations) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Expression(org.springframework.expression.Expression) TransactionStatus(org.springframework.transaction.TransactionStatus) Log(org.apache.commons.logging.Log) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) LogFactory(org.apache.commons.logging.LogFactory) MapSession(org.springframework.session.MapSession) Collections(java.util.Collections) ResultSetExtractor(org.springframework.jdbc.core.ResultSetExtractor) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) TransactionStatus(org.springframework.transaction.TransactionStatus) ArrayList(java.util.ArrayList) List(java.util.List) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult)

Example 12 with Session

use of org.springframework.session.Session in project spring-session by spring-projects.

the class JdbcOperationsSessionRepositoryTests method findByIndexNameAndIndexValuePrincipalIndexNameFound.

@Test
@SuppressWarnings("unchecked")
public void findByIndexNameAndIndexValuePrincipalIndexNameFound() {
    String principal = "username";
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, "notused", AuthorityUtils.createAuthorityList("ROLE_USER"));
    List<Session> saved = new ArrayList<>(2);
    Session saved1 = this.repository.new JdbcSession();
    saved1.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
    saved.add(saved1);
    Session saved2 = this.repository.new JdbcSession();
    saved2.setAttribute(SPRING_SECURITY_CONTEXT, authentication);
    saved.add(saved2);
    given(this.jdbcOperations.query(isA(String.class), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class))).willReturn(saved);
    Map<String, JdbcOperationsSessionRepository.JdbcSession> sessions = this.repository.findByIndexNameAndIndexValue(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, principal);
    assertThat(sessions).hasSize(2);
    assertPropagationRequiresNew();
    verify(this.jdbcOperations, times(1)).query(isA(String.class), isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));
}
Also used : Authentication(org.springframework.security.core.Authentication) ArrayList(java.util.ArrayList) ResultSetExtractor(org.springframework.jdbc.core.ResultSetExtractor) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BatchPreparedStatementSetter(org.springframework.jdbc.core.BatchPreparedStatementSetter) PreparedStatementSetter(org.springframework.jdbc.core.PreparedStatementSetter) Session(org.springframework.session.Session) MapSession(org.springframework.session.MapSession) Test(org.junit.Test)

Example 13 with Session

use of org.springframework.session.Session in project spring-session by spring-projects.

the class CookieHttpSessionIdResolverTests method onNewSessionTwiceNewId.

@Test
public void onNewSessionTwiceNewId() throws Exception {
    Session newSession = new MapSession();
    this.strategy.setSessionId(this.request, this.response, this.session.getId());
    this.strategy.setSessionId(this.request, this.response, newSession.getId());
    Cookie[] cookies = this.response.getCookies();
    assertThat(cookies).hasSize(2);
    assertThat(base64Decode(cookies[0].getValue())).isEqualTo(this.session.getId());
    assertThat(base64Decode(cookies[1].getValue())).isEqualTo(newSession.getId());
}
Also used : Cookie(javax.servlet.http.Cookie) MapSession(org.springframework.session.MapSession) Session(org.springframework.session.Session) MapSession(org.springframework.session.MapSession) Test(org.junit.Test)

Example 14 with Session

use of org.springframework.session.Session in project spring-session by spring-projects.

the class SpringSessionBackedSessionRegistryTest method expireNow.

@Test
public void expireNow() {
    Session session = createSession(SESSION_ID, USER_NAME, NOW);
    when(this.sessionRepository.findById(SESSION_ID)).thenReturn(session);
    SessionInformation sessionInfo = this.sessionRegistry.getSessionInformation(SESSION_ID);
    assertThat(sessionInfo.isExpired()).isFalse();
    sessionInfo.expireNow();
    assertThat(sessionInfo.isExpired()).isTrue();
    ArgumentCaptor<Session> captor = ArgumentCaptor.forClass(Session.class);
    verify(this.sessionRepository).save(captor.capture());
    assertThat(captor.getValue().<Boolean>getAttribute(SpringSessionBackedSessionInformation.EXPIRED_ATTR)).isEqualTo(Boolean.TRUE);
}
Also used : SessionInformation(org.springframework.security.core.session.SessionInformation) Session(org.springframework.session.Session) MapSession(org.springframework.session.MapSession) Test(org.junit.Test)

Example 15 with Session

use of org.springframework.session.Session in project spring-cloud by Rogge666.

the class SessionFilter method run.

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpSession httpSession = ctx.getRequest().getSession();
    Session session = repository.getSession(httpSession.getId());
    ctx.addZuulRequestHeader("Cookie", "SESSION=" + session.getId());
    return null;
}
Also used : HttpSession(javax.servlet.http.HttpSession) RequestContext(com.netflix.zuul.context.RequestContext) HttpSession(javax.servlet.http.HttpSession) Session(org.springframework.session.Session)

Aggregations

Session (org.springframework.session.Session)27 Test (org.junit.Test)19 MapSession (org.springframework.session.MapSession)19 HttpSession (javax.servlet.http.HttpSession)4 BatchPreparedStatementSetter (org.springframework.jdbc.core.BatchPreparedStatementSetter)4 ResultSetExtractor (org.springframework.jdbc.core.ResultSetExtractor)4 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)4 Authentication (org.springframework.security.core.Authentication)4 RedisSession (org.springframework.session.data.redis.RedisOperationsSessionRepository.RedisSession)4 SessionCreatedEvent (org.springframework.session.events.SessionCreatedEvent)4 PreparedStatementSetter (org.springframework.jdbc.core.PreparedStatementSetter)3 EnableJdbcHttpSession (org.springframework.session.jdbc.config.annotation.web.http.EnableJdbcHttpSession)3 RequestContext (com.netflix.zuul.context.RequestContext)2 Instant (java.time.Instant)2 ArrayList (java.util.ArrayList)2 SecurityContext (org.springframework.security.core.context.SecurityContext)2 SessionInformation (org.springframework.security.core.session.SessionInformation)2 EnableRedisHttpSession (org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession)2 EnableRedisWebSession (org.springframework.session.data.redis.config.annotation.web.server.EnableRedisWebSession)2 IOException (java.io.IOException)1