Add JacksonMongoSessionConverter
Fixes gh-416
This commit is contained in:
committed by
Rob Winch
parent
5cfbeae161
commit
e23398b890
@@ -15,17 +15,23 @@
|
||||
*/
|
||||
package org.springframework.session.data.mongo;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* Base class for serializing and deserializing session objects. To create custom
|
||||
@@ -40,6 +46,7 @@ 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.
|
||||
@@ -72,4 +79,39 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter
|
||||
.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));
|
||||
}
|
||||
|
||||
public Object convert(Object source, TypeDescriptor sourceType,
|
||||
TypeDescriptor targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (DBObject.class.isAssignableFrom(sourceType.getType())) {
|
||||
return convert((DBObject) source);
|
||||
}
|
||||
else {
|
||||
return convert((MongoExpiringSession) source);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract DBObject convert(MongoExpiringSession session);
|
||||
|
||||
protected abstract MongoExpiringSession convert(DBObject sessionWrapper);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
* 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 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;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.session.FindByIndexNameSessionRepository;
|
||||
|
||||
/**
|
||||
* {@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(DBObject 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,26 +20,22 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.mongodb.BasicDBObject;
|
||||
import com.mongodb.DBObject;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
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;
|
||||
|
||||
/**
|
||||
* {@code AbstractMongoSessionConverter} implementation transforming.
|
||||
* {@code MongoExpiringSession} to/from a BSON object using standard Java serialization
|
||||
* {@code AbstractMongoSessionConverter} implementation using standard Java serialization.
|
||||
*
|
||||
* @author Jakub Kubrynski
|
||||
* @since 1.2
|
||||
@@ -55,7 +51,6 @@ class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
|
||||
private static final String ATTRIBUTES = "attr";
|
||||
|
||||
private static final String PRINCIPAL_FIELD_NAME = "principal";
|
||||
private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";
|
||||
|
||||
@Override
|
||||
public Query getQueryForIndex(String indexName, Object indexValue) {
|
||||
@@ -66,26 +61,8 @@ class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
|
||||
return null;
|
||||
}
|
||||
|
||||
public Set<ConvertiblePair> getConvertibleTypes() {
|
||||
return Collections.singleton(
|
||||
new ConvertiblePair(DBObject.class, MongoExpiringSession.class));
|
||||
}
|
||||
|
||||
public Object convert(Object source, TypeDescriptor sourceType,
|
||||
TypeDescriptor targetType) {
|
||||
if (source == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (DBObject.class.isAssignableFrom(sourceType.getType())) {
|
||||
return convert((DBObject) source);
|
||||
}
|
||||
else {
|
||||
return convert((MongoExpiringSession) source);
|
||||
}
|
||||
}
|
||||
|
||||
private DBObject convert(MongoExpiringSession session) {
|
||||
@Override
|
||||
protected DBObject convert(MongoExpiringSession session) {
|
||||
BasicDBObject basicDBObject = new BasicDBObject();
|
||||
basicDBObject.put(ID, session.getId());
|
||||
basicDBObject.put(CREATION_TIME, session.getCreationTime());
|
||||
@@ -97,6 +74,18 @@ class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
|
||||
return basicDBObject;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected MongoExpiringSession convert(DBObject sessionWrapper) {
|
||||
MongoExpiringSession session = new MongoExpiringSession(
|
||||
(String) sessionWrapper.get(ID),
|
||||
(Integer) sessionWrapper.get(MAX_INTERVAL));
|
||||
session.setCreationTime((Long) sessionWrapper.get(CREATION_TIME));
|
||||
session.setLastAccessedTime((Long) sessionWrapper.get(LAST_ACCESSED_TIME));
|
||||
session.setExpireAt((Date) sessionWrapper.get(EXPIRE_AT_FIELD_NAME));
|
||||
deserializeAttributes(sessionWrapper, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
private byte[] serializeAttributes(Session session) {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
@@ -115,29 +104,6 @@ class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
|
||||
}
|
||||
}
|
||||
|
||||
private 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);
|
||||
}
|
||||
}
|
||||
|
||||
private MongoExpiringSession convert(DBObject sessionWrapper) {
|
||||
MongoExpiringSession session = new MongoExpiringSession(
|
||||
(String) sessionWrapper.get(ID),
|
||||
(Integer) sessionWrapper.get(MAX_INTERVAL));
|
||||
session.setCreationTime((Long) sessionWrapper.get(CREATION_TIME));
|
||||
session.setLastAccessedTime((Long) sessionWrapper.get(LAST_ACCESSED_TIME));
|
||||
session.setExpireAt((Date) sessionWrapper.get(EXPIRE_AT_FIELD_NAME));
|
||||
deserializeAttributes(sessionWrapper, session);
|
||||
return session;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void deserializeAttributes(DBObject sessionWrapper, Session session) {
|
||||
try {
|
||||
|
||||
@@ -17,6 +17,7 @@ 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;
|
||||
@@ -32,6 +33,11 @@ import org.springframework.session.ExpiringSession;
|
||||
*/
|
||||
public class MongoExpiringSession implements ExpiringSession {
|
||||
|
||||
/**
|
||||
* Mongo doesn't support {@literal dot} in field names. We replace it with very rarely used character
|
||||
*/
|
||||
private static final char DOT_COVER_CHAR = '\uF607';
|
||||
|
||||
private final String id;
|
||||
private long created = System.currentTimeMillis();
|
||||
private long accessed;
|
||||
@@ -59,24 +65,28 @@ public class MongoExpiringSession implements ExpiringSession {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getAttribute(String attributeName) {
|
||||
return (T) this.attrs.get(attributeName);
|
||||
return (T) this.attrs.get(coverDot(attributeName));
|
||||
}
|
||||
|
||||
public Set<String> getAttributeNames() {
|
||||
return this.attrs.keySet();
|
||||
HashSet<String> result = new HashSet<String>();
|
||||
for (String key : this.attrs.keySet()) {
|
||||
result.add(uncoverDot(key));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setAttribute(String attributeName, Object attributeValue) {
|
||||
if (attributeValue == null) {
|
||||
removeAttribute(attributeName);
|
||||
removeAttribute(coverDot(attributeName));
|
||||
}
|
||||
else {
|
||||
this.attrs.put(attributeName, attributeValue);
|
||||
this.attrs.put(coverDot(attributeName), attributeValue);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeAttribute(String attributeName) {
|
||||
this.attrs.remove(attributeName);
|
||||
this.attrs.remove(coverDot(attributeName));
|
||||
}
|
||||
|
||||
public long getCreationTime() {
|
||||
@@ -117,6 +127,14 @@ public class MongoExpiringSession implements ExpiringSession {
|
||||
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) {
|
||||
@@ -129,7 +147,6 @@ public class MongoExpiringSession implements ExpiringSession {
|
||||
MongoExpiringSession that = (MongoExpiringSession) o;
|
||||
|
||||
return this.id.equals(that.id);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -19,7 +19,6 @@ import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import com.mongodb.DBObject;
|
||||
@@ -56,7 +55,7 @@ public class MongoOperationsSessionRepository
|
||||
|
||||
private final MongoOperations mongoOperations;
|
||||
|
||||
private AbstractMongoSessionConverter mongoSessionConverter = new JdkMongoSessionConverter();
|
||||
private AbstractMongoSessionConverter mongoSessionConverter = SessionConverterProvider.get();
|
||||
private Integer maxInactiveIntervalInSeconds = DEFAULT_INACTIVE_INTERVAL;
|
||||
private String collectionName = DEFAULT_COLLECTION_NAME;
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* 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 get() {
|
||||
if (ClassUtils.isPresent(JACKSON_CLASS_NAME, null)) {
|
||||
return new JacksonMongoSessionConverter();
|
||||
}
|
||||
else {
|
||||
return new JdkMongoSessionConverter();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user