Enable Spring Session MongoDB
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.bson.Document;
|
||||
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.core.convert.converter.GenericConverter;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.mongodb.core.IndexOperations;
|
||||
import org.springframework.data.mongodb.core.index.Index;
|
||||
import org.springframework.data.mongodb.core.index.IndexInfo;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
import org.springframework.session.Session;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* Base class for serializing and deserializing session objects. To create custom
|
||||
* serializer you have to implement this interface and simply register your class as a
|
||||
* bean.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @since 1.2
|
||||
*/
|
||||
public abstract class AbstractMongoSessionConverter implements GenericConverter {
|
||||
|
||||
private static final Log LOG = LogFactory.getLog(AbstractMongoSessionConverter.class);
|
||||
|
||||
protected static final String EXPIRE_AT_FIELD_NAME = "expireAt";
|
||||
|
||||
private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";
|
||||
|
||||
/**
|
||||
* Returns query to be executed to return sessions based on a particular index.
|
||||
* @param indexName name of the index
|
||||
* @param indexValue value to query against
|
||||
* @return built query or null if indexName is not supported
|
||||
*/
|
||||
protected abstract Query getQueryForIndex(String indexName, Object indexValue);
|
||||
|
||||
/**
|
||||
* Method ensures that there is a TTL index on {@literal expireAt} field. It's has
|
||||
* {@literal expireAfterSeconds} set to zero seconds, so the expiration time is
|
||||
* controlled by the application.
|
||||
*
|
||||
* It can be extended in custom converters when there is a need for creating
|
||||
* additional custom indexes.
|
||||
* @param sessionCollectionIndexes {@link IndexOperations} to use
|
||||
*/
|
||||
protected void ensureIndexes(IndexOperations sessionCollectionIndexes) {
|
||||
|
||||
for (IndexInfo info : sessionCollectionIndexes.getIndexInfo()) {
|
||||
if (EXPIRE_AT_FIELD_NAME.equals(info.getName())) {
|
||||
LOG.debug("TTL index on field " + EXPIRE_AT_FIELD_NAME + " already exists");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
LOG.info("Creating TTL index on field " + EXPIRE_AT_FIELD_NAME);
|
||||
sessionCollectionIndexes
|
||||
.ensureIndex(new Index(EXPIRE_AT_FIELD_NAME, Sort.Direction.ASC).named(EXPIRE_AT_FIELD_NAME).expire(0));
|
||||
}
|
||||
|
||||
protected String extractPrincipal(Session expiringSession) {
|
||||
|
||||
String resolvedPrincipal = AuthenticationParser.extractName(expiringSession.getAttribute(SPRING_SECURITY_CONTEXT));
|
||||
|
||||
if (resolvedPrincipal != null) {
|
||||
return resolvedPrincipal;
|
||||
} else {
|
||||
return expiringSession.getAttribute(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
public Set<ConvertiblePair> getConvertibleTypes() {
|
||||
|
||||
return Collections.singleton(
|
||||
new ConvertiblePair(DBObject.class, MongoExpiringSession.class));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
|
||||
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (DBObject.class.isAssignableFrom(sourceType.getType())) {
|
||||
return convert(new Document(((DBObject) source).toMap()));
|
||||
}
|
||||
else if (Document.class.isAssignableFrom(sourceType.getType())) {
|
||||
return convert((Document) source);
|
||||
}
|
||||
else {
|
||||
return convert((MongoExpiringSession) source);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract DBObject convert(MongoExpiringSession session);
|
||||
|
||||
protected abstract MongoExpiringSession convert(Document sessionWrapper);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
|
||||
/**
|
||||
* Utility class to extract principal name from {@code Authentication} object.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
*/
|
||||
final class AuthenticationParser {
|
||||
|
||||
private static final String NAME_EXPRESSION = "authentication?.name";
|
||||
|
||||
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
|
||||
|
||||
/**
|
||||
* Extracts principal name from authentication.
|
||||
*
|
||||
* @param authentication Authentication object
|
||||
* @return principal name
|
||||
*/
|
||||
static String extractName(Object authentication) {
|
||||
|
||||
if (authentication != null) {
|
||||
Expression expression = PARSER.parseExpression(NAME_EXPRESSION);
|
||||
return expression.getValue(authentication, String.class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private AuthenticationParser() {}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.bson.Document;
|
||||
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.Module;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
|
||||
import com.mongodb.DBObject;
|
||||
import com.mongodb.util.JSON;
|
||||
|
||||
/**
|
||||
* {@code AbstractMongoSessionConverter} implementation using Jackson.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @since 1.2
|
||||
*/
|
||||
public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter {
|
||||
|
||||
private static final Log LOG = LogFactory.getLog(JacksonMongoSessionConverter.class);
|
||||
|
||||
private static final String ATTRS_FIELD_NAME = "attrs.";
|
||||
private static final String PRINCIPAL_FIELD_NAME = "principal";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public JacksonMongoSessionConverter() {
|
||||
this(Collections.<Module>emptyList());
|
||||
}
|
||||
|
||||
public JacksonMongoSessionConverter(Iterable<Module> modules) {
|
||||
|
||||
this.objectMapper = buildObjectMapper();
|
||||
this.objectMapper.registerModules(modules);
|
||||
}
|
||||
|
||||
protected Query getQueryForIndex(String indexName, Object indexValue) {
|
||||
|
||||
if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
|
||||
return Query.query(Criteria.where(PRINCIPAL_FIELD_NAME).is(indexValue));
|
||||
}
|
||||
return Query.query(Criteria.where(ATTRS_FIELD_NAME +
|
||||
MongoExpiringSession.coverDot(indexName)).is(indexValue));
|
||||
}
|
||||
|
||||
private ObjectMapper buildObjectMapper() {
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// serialize fields instead of properties
|
||||
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
|
||||
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
|
||||
|
||||
// ignore unresolved fields (mostly 'principal')
|
||||
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
objectMapper.setPropertyNamingStrategy(new MongoIdNamingStrategy());
|
||||
|
||||
return objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DBObject convert(MongoExpiringSession source) {
|
||||
|
||||
try {
|
||||
DBObject dbSession = (DBObject) JSON.parse(this.objectMapper.writeValueAsString(source));
|
||||
dbSession.put(PRINCIPAL_FIELD_NAME, extractPrincipal(source));
|
||||
return dbSession;
|
||||
}
|
||||
catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Cannot convert MongoExpiringSession", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MongoExpiringSession convert(Document source) {
|
||||
|
||||
String json = JSON.serialize(source);
|
||||
|
||||
try {
|
||||
return this.objectMapper.readValue(json, MongoExpiringSession.class);
|
||||
}
|
||||
catch (IOException e) {
|
||||
LOG.error("Error during Mongo Session deserialization", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static class MongoIdNamingStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase {
|
||||
|
||||
@Override
|
||||
public String translate(String propertyName) {
|
||||
if (propertyName.equals("id")) {
|
||||
return "_id";
|
||||
}
|
||||
else if (propertyName.equals("_id")) {
|
||||
return "id";
|
||||
}
|
||||
return propertyName;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.bson.Document;
|
||||
import org.bson.types.Binary;
|
||||
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.core.serializer.support.DeserializingConverter;
|
||||
import org.springframework.core.serializer.support.SerializingConverter;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
import org.springframework.session.Session;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* {@code AbstractMongoSessionConverter} implementation using standard Java serialization.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @author Rob Winch
|
||||
* @since 1.2
|
||||
*/
|
||||
public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
|
||||
|
||||
private static final String ID = "_id";
|
||||
private static final String CREATION_TIME = "created";
|
||||
private static final String LAST_ACCESSED_TIME = "accessed";
|
||||
private static final String MAX_INTERVAL = "interval";
|
||||
private static final String ATTRIBUTES = "attr";
|
||||
private static final String PRINCIPAL_FIELD_NAME = "principal";
|
||||
|
||||
private final Converter<Object, byte[]> serializer;
|
||||
private final Converter<byte[], Object> deserializer;
|
||||
|
||||
public JdkMongoSessionConverter() {
|
||||
this(new SerializingConverter(), new DeserializingConverter());
|
||||
}
|
||||
|
||||
public JdkMongoSessionConverter(Converter<Object, byte[]> serializer,
|
||||
Converter<byte[], Object> deserializer) {
|
||||
|
||||
Assert.notNull(serializer, "serializer cannot be null");
|
||||
Assert.notNull(deserializer, "deserializer cannot be null");
|
||||
this.serializer = serializer;
|
||||
this.deserializer = deserializer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Query getQueryForIndex(String indexName, Object indexValue) {
|
||||
|
||||
if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME
|
||||
.equals(indexName)) {
|
||||
return Query.query(Criteria.where(PRINCIPAL_FIELD_NAME).is(indexValue));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DBObject convert(MongoExpiringSession session) {
|
||||
|
||||
BasicDBObject basicDBObject = new BasicDBObject();
|
||||
basicDBObject.put(ID, session.getId());
|
||||
basicDBObject.put(CREATION_TIME, session.getCreationTime());
|
||||
basicDBObject.put(LAST_ACCESSED_TIME, session.getLastAccessedTime());
|
||||
basicDBObject.put(MAX_INTERVAL, session.getMaxInactiveIntervalInSeconds());
|
||||
basicDBObject.put(PRINCIPAL_FIELD_NAME, extractPrincipal(session));
|
||||
basicDBObject.put(EXPIRE_AT_FIELD_NAME, session.getExpireAt());
|
||||
basicDBObject.put(ATTRIBUTES, serializeAttributes(session));
|
||||
return basicDBObject;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MongoExpiringSession convert(Document sessionWrapper) {
|
||||
|
||||
MongoExpiringSession session = new MongoExpiringSession(
|
||||
sessionWrapper.getString(ID), sessionWrapper.getInteger(MAX_INTERVAL));
|
||||
|
||||
session.setCreationTime(sessionWrapper.getLong(CREATION_TIME));
|
||||
session.setLastAccessedTime(sessionWrapper.getLong(LAST_ACCESSED_TIME));
|
||||
session.setExpireAt((Date) sessionWrapper.get(EXPIRE_AT_FIELD_NAME));
|
||||
deserializeAttributes(sessionWrapper, session);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
private byte[] serializeAttributes(Session session) {
|
||||
|
||||
Map<String, Object> attributes = new HashMap<>();
|
||||
|
||||
for (String attrName : session.getAttributeNames()) {
|
||||
attributes.put(attrName, session.getAttribute(attrName));
|
||||
}
|
||||
|
||||
return this.serializer.convert(attributes);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void deserializeAttributes(Document sessionWrapper, Session session) {
|
||||
|
||||
Object sessionAttributes = sessionWrapper.get(ATTRIBUTES);
|
||||
|
||||
byte[] attributesBytes = (sessionAttributes instanceof Binary
|
||||
? ((Binary) sessionAttributes).getData() : (byte[]) sessionAttributes);
|
||||
|
||||
Map<String, Object> attributes = (Map<String, Object>) this.deserializer.convert(attributesBytes);
|
||||
|
||||
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
|
||||
session.setAttribute(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.springframework.session.ExpiringSession;
|
||||
|
||||
/**
|
||||
* Session object providing additional information about the datetime of expiration.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @since 1.2
|
||||
*/
|
||||
public class MongoExpiringSession implements ExpiringSession {
|
||||
|
||||
/**
|
||||
* Mongo doesn't support {@literal dot} in field names. We replace it with a very rarely used character
|
||||
*/
|
||||
private static final char DOT_COVER_CHAR = '\uF607';
|
||||
|
||||
private final String id;
|
||||
private long created = System.currentTimeMillis();
|
||||
private long accessed;
|
||||
private int interval;
|
||||
private Date expireAt;
|
||||
private Map<String, Object> attrs = new HashMap<String, Object>();
|
||||
|
||||
public MongoExpiringSession() {
|
||||
this(MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL);
|
||||
}
|
||||
|
||||
public MongoExpiringSession(int maxInactiveIntervalInSeconds) {
|
||||
this(UUID.randomUUID().toString(), maxInactiveIntervalInSeconds);
|
||||
}
|
||||
|
||||
public MongoExpiringSession(String id, int maxInactiveIntervalInSeconds) {
|
||||
|
||||
this.id = id;
|
||||
this.interval = maxInactiveIntervalInSeconds;
|
||||
setLastAccessedTime(this.created);
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getAttribute(String attributeName) {
|
||||
return (T) this.attrs.get(coverDot(attributeName));
|
||||
}
|
||||
|
||||
public Set<String> getAttributeNames() {
|
||||
|
||||
HashSet<String> result = new HashSet<>();
|
||||
|
||||
for (String key : this.attrs.keySet()) {
|
||||
result.add(uncoverDot(key));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setAttribute(String attributeName, Object attributeValue) {
|
||||
|
||||
if (attributeValue == null) {
|
||||
removeAttribute(coverDot(attributeName));
|
||||
} else {
|
||||
this.attrs.put(coverDot(attributeName), attributeValue);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAttribute(String attributeName) {
|
||||
this.attrs.remove(coverDot(attributeName));
|
||||
}
|
||||
|
||||
public long getCreationTime() {
|
||||
return this.created;
|
||||
}
|
||||
|
||||
public void setCreationTime(long created) {
|
||||
this.created = created;
|
||||
}
|
||||
|
||||
public void setLastAccessedTime(long lastAccessedTime) {
|
||||
|
||||
this.accessed = lastAccessedTime;
|
||||
this.expireAt = new Date(lastAccessedTime + TimeUnit.SECONDS.toMillis(this.interval));
|
||||
}
|
||||
|
||||
public long getLastAccessedTime() {
|
||||
return this.accessed;
|
||||
}
|
||||
|
||||
public void setMaxInactiveIntervalInSeconds(int interval) {
|
||||
this.interval = interval;
|
||||
}
|
||||
|
||||
public int getMaxInactiveIntervalInSeconds() {
|
||||
return this.interval;
|
||||
}
|
||||
|
||||
public boolean isExpired() {
|
||||
return this.interval >= 0 && new Date().after(this.expireAt);
|
||||
}
|
||||
|
||||
public Date getExpireAt() {
|
||||
return this.expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(Date expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
static String coverDot(String attributeName) {
|
||||
return attributeName.replace('.', DOT_COVER_CHAR);
|
||||
}
|
||||
|
||||
static String uncoverDot(String attributeName) {
|
||||
return attributeName.replace(DOT_COVER_CHAR, '.');
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
MongoExpiringSession that = (MongoExpiringSession) o;
|
||||
|
||||
return this.id.equals(that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return this.id.hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
/*
|
||||
* Copyright 2014-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import org.bson.Document;
|
||||
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.data.mongodb.core.IndexOperations;
|
||||
import org.springframework.data.mongodb.core.MongoOperations;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
|
||||
/**
|
||||
* Session repository implementation which stores sessions in Mongo. Uses
|
||||
* {@link AbstractMongoSessionConverter} to transform session objects from/to native Mongo
|
||||
* representation ({@code DBObject}).
|
||||
*
|
||||
* Repository is also responsible for removing expired sessions from database. Cleanup is
|
||||
* done every minute.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @since 1.2
|
||||
*/
|
||||
public class MongoOperationsSessionRepository
|
||||
implements FindByIndexNameSessionRepository<MongoExpiringSession> {
|
||||
|
||||
/**
|
||||
* The default time period in seconds in which a session will expire.
|
||||
*/
|
||||
public static final int DEFAULT_INACTIVE_INTERVAL = 1800;
|
||||
|
||||
/**
|
||||
* the default collection name for storing session.
|
||||
*/
|
||||
public static final String DEFAULT_COLLECTION_NAME = "sessions";
|
||||
|
||||
private final MongoOperations mongoOperations;
|
||||
|
||||
private AbstractMongoSessionConverter mongoSessionConverter =
|
||||
SessionConverterProvider.getDefaultMongoConverter();
|
||||
|
||||
private Integer maxInactiveIntervalInSeconds = DEFAULT_INACTIVE_INTERVAL;
|
||||
private String collectionName = DEFAULT_COLLECTION_NAME;
|
||||
|
||||
public MongoOperationsSessionRepository(MongoOperations mongoOperations) {
|
||||
this.mongoOperations = mongoOperations;
|
||||
}
|
||||
|
||||
public MongoExpiringSession createSession() {
|
||||
|
||||
MongoExpiringSession session = new MongoExpiringSession();
|
||||
|
||||
if (this.maxInactiveIntervalInSeconds != null) {
|
||||
session.setMaxInactiveIntervalInSeconds(this.maxInactiveIntervalInSeconds);
|
||||
}
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
public void save(MongoExpiringSession session) {
|
||||
|
||||
DBObject sessionDbObject = convertToDBObject(session);
|
||||
this.mongoOperations.save(sessionDbObject, this.collectionName);
|
||||
}
|
||||
|
||||
public MongoExpiringSession getSession(String id) {
|
||||
|
||||
Document sessionWrapper = findSession(id);
|
||||
|
||||
if (sessionWrapper == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
MongoExpiringSession session = convertToSession(sessionWrapper);
|
||||
|
||||
if (session.isExpired()) {
|
||||
delete(id);
|
||||
return null;
|
||||
}
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Currently this repository allows only querying against
|
||||
* {@code PRINCIPAL_NAME_INDEX_NAME}.
|
||||
*
|
||||
* @param indexName the name if the index (i.e.
|
||||
* {@link FindByIndexNameSessionRepository#PRINCIPAL_NAME_INDEX_NAME})
|
||||
* @param indexValue the value of the index to search for.
|
||||
* @return sessions map
|
||||
*/
|
||||
public Map<String, MongoExpiringSession> findByIndexNameAndIndexValue(String indexName, String indexValue) {
|
||||
|
||||
HashMap<String, MongoExpiringSession> result = new HashMap<String, MongoExpiringSession>();
|
||||
|
||||
Query query = this.mongoSessionConverter.getQueryForIndex(indexName, indexValue);
|
||||
|
||||
if (query == null) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
List<Document> mapSessions = this.mongoOperations.find(query, Document.class, this.collectionName);
|
||||
|
||||
for (Document dbSession : mapSessions) {
|
||||
MongoExpiringSession mapSession = convertToSession(dbSession);
|
||||
result.put(mapSession.getId(), mapSession);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void delete(String id) {
|
||||
this.mongoOperations.remove(findSession(id), this.collectionName);
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void ensureIndexesAreCreated() {
|
||||
|
||||
IndexOperations indexOperations = this.mongoOperations.indexOps(this.collectionName);
|
||||
this.mongoSessionConverter.ensureIndexes(indexOperations);
|
||||
}
|
||||
|
||||
Document findSession(String id) {
|
||||
return this.mongoOperations.findById(id, Document.class, this.collectionName);
|
||||
}
|
||||
|
||||
MongoExpiringSession convertToSession(Document session) {
|
||||
|
||||
return (MongoExpiringSession) this.mongoSessionConverter.convert(session,
|
||||
TypeDescriptor.valueOf(Document.class),
|
||||
TypeDescriptor.valueOf(MongoExpiringSession.class));
|
||||
}
|
||||
|
||||
DBObject convertToDBObject(MongoExpiringSession session) {
|
||||
|
||||
return (DBObject) this.mongoSessionConverter.convert(session,
|
||||
TypeDescriptor.valueOf(MongoExpiringSession.class),
|
||||
TypeDescriptor.valueOf(DBObject.class));
|
||||
}
|
||||
|
||||
public void setMongoSessionConverter(AbstractMongoSessionConverter mongoSessionConverter) {
|
||||
this.mongoSessionConverter = mongoSessionConverter;
|
||||
}
|
||||
|
||||
public void setMaxInactiveIntervalInSeconds(Integer maxInactiveIntervalInSeconds) {
|
||||
this.maxInactiveIntervalInSeconds = maxInactiveIntervalInSeconds;
|
||||
}
|
||||
|
||||
public void setCollectionName(String collectionName) {
|
||||
this.collectionName = collectionName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Provider choosing proper AbstractMongoSessionConverter.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
*/
|
||||
final class SessionConverterProvider {
|
||||
|
||||
private static final String JACKSON_CLASS_NAME = "com.fasterxml.jackson.databind.ObjectMapper";
|
||||
|
||||
private SessionConverterProvider() {
|
||||
}
|
||||
|
||||
static AbstractMongoSessionConverter getDefaultMongoConverter() {
|
||||
|
||||
if (ClassUtils.isPresent(JACKSON_CLASS_NAME, null)) {
|
||||
return new JacksonMongoSessionConverter();
|
||||
}
|
||||
else {
|
||||
return new JdkMongoSessionConverter();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.session.data.mongo.config.annotation.web.http;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.session.data.mongo.MongoOperationsSessionRepository;
|
||||
|
||||
/**
|
||||
* Add this annotation to a {@code @Configuration} class to expose the
|
||||
* SessionRepositoryFilter as a bean named "springSessionRepositoryFilter" and backed by
|
||||
* Mongo. Use {@code collectionName} to change default name of the collection used to
|
||||
* store sessions. <pre>
|
||||
* <code>
|
||||
* {@literal @EnableMongoHttpSession}
|
||||
* public class MongoHttpSessionConfig {
|
||||
*
|
||||
* {@literal @Bean}
|
||||
* public MongoOperations mongoOperations() throws UnknownHostException {
|
||||
* return new MongoTemplate(new MongoClient(), "databaseName");
|
||||
* }
|
||||
*
|
||||
* }
|
||||
* </code> </pre>
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @since 1.2
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.TYPE)
|
||||
@Documented
|
||||
@Import(MongoHttpSessionConfiguration.class)
|
||||
@Configuration
|
||||
public @interface EnableMongoHttpSession {
|
||||
|
||||
/**
|
||||
* The maximum time a session will be kept if it is inactive.
|
||||
*
|
||||
* @return default max inactive interval in seconds
|
||||
*/
|
||||
int maxInactiveIntervalInSeconds() default MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL;
|
||||
|
||||
/**
|
||||
* The collection name to use.
|
||||
*
|
||||
* @return name of the collection to store session
|
||||
*/
|
||||
String collectionName() default MongoOperationsSessionRepository.DEFAULT_COLLECTION_NAME;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* Copyright 2014-2016 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.springframework.session.data.mongo.config.annotation.web.http;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.EmbeddedValueResolverAware;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.ImportAware;
|
||||
import org.springframework.core.annotation.AnnotationAttributes;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.data.mongodb.core.MongoOperations;
|
||||
import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration;
|
||||
import org.springframework.session.data.mongo.AbstractMongoSessionConverter;
|
||||
import org.springframework.session.data.mongo.MongoOperationsSessionRepository;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.util.StringValueResolver;
|
||||
|
||||
/**
|
||||
* Configuration class registering {@code MongoSessionRepository} bean. To import this
|
||||
* configuration use {@link EnableMongoHttpSession} annotation.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @author Eddú Meléndez
|
||||
* @since 1.2
|
||||
*/
|
||||
@Configuration
|
||||
public class MongoHttpSessionConfiguration extends SpringHttpSessionConfiguration
|
||||
implements EmbeddedValueResolverAware, ImportAware {
|
||||
|
||||
private AbstractMongoSessionConverter mongoSessionConverter;
|
||||
|
||||
private Integer maxInactiveIntervalInSeconds;
|
||||
private String collectionName;
|
||||
|
||||
private StringValueResolver embeddedValueResolver;
|
||||
|
||||
@Bean
|
||||
public MongoOperationsSessionRepository mongoSessionRepository(MongoOperations mongoOperations) {
|
||||
|
||||
MongoOperationsSessionRepository repository = new MongoOperationsSessionRepository(mongoOperations);
|
||||
repository.setMaxInactiveIntervalInSeconds(this.maxInactiveIntervalInSeconds);
|
||||
|
||||
if (this.mongoSessionConverter != null) {
|
||||
repository.setMongoSessionConverter(this.mongoSessionConverter);
|
||||
}
|
||||
|
||||
if (StringUtils.hasText(this.collectionName)) {
|
||||
repository.setCollectionName(this.collectionName);
|
||||
}
|
||||
|
||||
return repository;
|
||||
}
|
||||
|
||||
public void setCollectionName(String collectionName) {
|
||||
this.collectionName = collectionName;
|
||||
}
|
||||
|
||||
public void setMaxInactiveIntervalInSeconds(Integer maxInactiveIntervalInSeconds) {
|
||||
this.maxInactiveIntervalInSeconds = maxInactiveIntervalInSeconds;
|
||||
}
|
||||
|
||||
public void setImportMetadata(AnnotationMetadata importMetadata) {
|
||||
|
||||
AnnotationAttributes attributes = AnnotationAttributes.fromMap(
|
||||
importMetadata.getAnnotationAttributes(EnableMongoHttpSession.class.getName()));
|
||||
|
||||
this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds");
|
||||
|
||||
String collectionNameValue = attributes.getString("collectionName");
|
||||
if (StringUtils.hasText(collectionNameValue)) {
|
||||
this.collectionName = this.embeddedValueResolver.resolveStringValue(collectionNameValue);
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired(required = false)
|
||||
public void setMongoSessionConverter(AbstractMongoSessionConverter mongoSessionConverter) {
|
||||
this.mongoSessionConverter = mongoSessionConverter;
|
||||
}
|
||||
|
||||
public void setEmbeddedValueResolver(StringValueResolver resolver) {
|
||||
this.embeddedValueResolver = resolver;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user