Add Nullable checks.

Resolves #55.
This commit is contained in:
Greg Turnquist
2019-03-12 11:22:39 -05:00
parent 6bf6419d57
commit 6c4baa00a6
20 changed files with 199 additions and 24 deletions

View File

@@ -73,6 +73,7 @@
<flapdoodle.version>1.50.5</flapdoodle.version>
<hamcrest.version>1.3</hamcrest.version>
<jackson.version>2.9.1</jackson.version>
<jsr305.version>3.0.2</jsr305.version>
<junit.version>4.12</junit.version>
<lombok.version>1.18.0</lombok.version>
<mockito.version>2.18.3</mockito.version>
@@ -529,6 +530,12 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>${jsr305.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>

View File

@@ -29,6 +29,7 @@ import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexInfo;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.lang.Nullable;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
@@ -55,6 +56,7 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter
* @param indexValue value to query against
* @return built query or null if indexName is not supported
*/
@Nullable
protected abstract Query getQueryForIndex(String indexName, Object indexValue);
/**
@@ -95,6 +97,7 @@ public abstract class AbstractMongoSessionConverter implements GenericConverter
}
@SuppressWarnings("unchecked")
@Nullable
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (source == null) {

View File

@@ -0,0 +1,36 @@
/*
* Copyright 2019 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.lang.Nullable;
/**
* @author Greg Turnquist
*/
public final class Assert {
private Assert() {}
public static <T> T requireNonNull(@Nullable T item, String message) {
if (item == null) {
throw new IllegalArgumentException(message);
}
return item;
}
}

View File

@@ -17,6 +17,7 @@ package org.springframework.session.data.mongo;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.lang.Nullable;
/**
* Utility class to extract principal name from {@code Authentication} object.
@@ -38,7 +39,8 @@ final class AuthenticationParser {
* @param authentication Authentication object
* @return principal name
*/
static String extractName(Object authentication) {
@Nullable
static String extractName(@Nullable Object authentication) {
if (authentication == null) {
return null;

View File

@@ -26,6 +26,7 @@ import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.lang.Nullable;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.util.Assert;
@@ -72,6 +73,7 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter
this.objectMapper = objectMapper;
}
@Nullable
protected Query getQueryForIndex(String indexName, Object indexValue) {
if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
@@ -114,6 +116,7 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter
}
@Override
@Nullable
protected MongoSession convert(Document source) {
String json = source.toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build());

View File

@@ -29,6 +29,7 @@ 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.lang.Nullable;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.util.Assert;
@@ -64,7 +65,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
public JdkMongoSessionConverter(Converter<Object, byte[]> serializer, Converter<byte[], Object> deserializer,
Duration maxInactiveInterval) {
Assert.notNull(serializer, "serializer cannot be null");
Assert.notNull(deserializer, "deserializer cannot be null");
Assert.notNull(maxInactiveInterval, "maxInactiveInterval cannot be null");
@@ -74,6 +75,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
}
@Override
@Nullable
public Query getQueryForIndex(String indexName, Object indexValue) {
if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
@@ -130,6 +132,7 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
return session;
}
@Nullable
private byte[] serializeAttributes(Session session) {
Map<String, Object> attributes = new HashMap<>();
@@ -151,8 +154,10 @@ public class JdkMongoSessionConverter extends AbstractMongoSessionConverter {
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());
if (attributes != null) {
for (Map.Entry<String, Object> entry : attributes.entrySet()) {
session.setAttribute(entry.getKey(), entry.getValue());
}
}
}
}

View File

@@ -35,6 +35,7 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.index.IndexOperations;
import org.springframework.lang.Nullable;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDeletedEvent;
@@ -89,10 +90,12 @@ public class MongoOperationsSessionRepository
@Override
public void save(MongoSession session) {
this.mongoOperations.save(convertToDBObject(this.mongoSessionConverter, session), this.collectionName);
this.mongoOperations.save(Assert.requireNonNull(convertToDBObject(this.mongoSessionConverter, session),
"convertToDBObject must not null!"), this.collectionName);
}
@Override
@Nullable
public MongoSession findById(String id) {
Document sessionWrapper = findSession(id);
@@ -103,7 +106,7 @@ public class MongoOperationsSessionRepository
MongoSession session = convertToSession(this.mongoSessionConverter, sessionWrapper);
if (session.isExpired()) {
if (session != null && session.isExpired()) {
publishEvent(new SessionExpiredEvent(this, session));
deleteById(id);
@@ -135,7 +138,12 @@ public class MongoOperationsSessionRepository
public void deleteById(String id) {
Optional.ofNullable(findSession(id)).ifPresent(document -> {
publishEvent(new SessionDeletedEvent(this, convertToSession(this.mongoSessionConverter, document)));
MongoSession session = convertToSession(this.mongoSessionConverter, document);
if (session != null) {
publishEvent(new SessionDeletedEvent(this, session));
}
this.mongoOperations.remove(document, this.collectionName);
});
}
@@ -147,6 +155,7 @@ public class MongoOperationsSessionRepository
this.mongoSessionConverter.ensureIndexes(indexOperations);
}
@Nullable
private Document findSession(String id) {
return this.mongoOperations.findById(id, Document.class, this.collectionName);
}

View File

@@ -28,6 +28,7 @@ import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.lang.Nullable;
import org.springframework.session.Session;
/**
@@ -83,6 +84,7 @@ public class MongoSession implements Session {
}
@Override
@Nullable
public <T> T getAttribute(String attributeName) {
return (T) this.attrs.get(coverDot(attributeName));
}

View File

@@ -17,6 +17,7 @@ package org.springframework.session.data.mongo;
import org.bson.Document;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.Nullable;
import com.mongodb.DBObject;
@@ -25,12 +26,14 @@ import com.mongodb.DBObject;
*/
public final class MongoSessionUtils {
@Nullable
static DBObject convertToDBObject(AbstractMongoSessionConverter mongoSessionConverter, MongoSession session) {
return (DBObject) mongoSessionConverter.convert(session, TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class));
}
@Nullable
static MongoSession convertToSession(AbstractMongoSessionConverter mongoSessionConverter, Document session) {
return (MongoSession) mongoSessionConverter.convert(session, TypeDescriptor.valueOf(Document.class),

View File

@@ -37,6 +37,8 @@ import org.springframework.session.ReactiveSessionRepository;
import org.springframework.session.events.SessionCreatedEvent;
import org.springframework.session.events.SessionDeletedEvent;
import com.mongodb.DBObject;
/**
* @author Greg Turnquist
*/
@@ -100,8 +102,12 @@ public class ReactiveMongoOperationsSessionRepository
@Override
public Mono<Void> save(MongoSession session) {
return this.mongoOperations.save(convertToDBObject(this.mongoSessionConverter, session), this.collectionName)
.then();
DBObject dbObject = convertToDBObject(this.mongoSessionConverter, session);
if (dbObject != null) {
return this.mongoOperations.save(dbObject, this.collectionName).then();
} else {
return Mono.empty();
}
}
/**

View File

@@ -88,9 +88,13 @@ public class MongoHttpSessionConfiguration extends SpringHttpSessionConfiguratio
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importMetadata.getAnnotationAttributes(EnableMongoHttpSession.class.getName()));
this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds");
if (attributes != null) {
this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds");
} else {
this.maxInactiveIntervalInSeconds = MongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL;
}
String collectionNameValue = attributes.getString("collectionName");
String collectionNameValue = attributes != null ? attributes.getString("collectionName") : "";
if (StringUtils.hasText(collectionNameValue)) {
this.collectionName = this.embeddedValueResolver.resolveStringValue(collectionNameValue);
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2019 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.
*/
/**
* @author Greg Turnquist
*/
@NonNullApi
package org.springframework.session.data.mongo.config.annotation.web.http;
import org.springframework.lang.NonNullApi;

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2019 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.
*/
/**
* @author Greg Turnquist
*/
@NonNullApi
package org.springframework.session.data.mongo.config.annotation.web;
import org.springframework.lang.NonNullApi;

View File

@@ -95,9 +95,13 @@ public class ReactiveMongoWebSessionConfiguration extends SpringWebSessionConfig
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importMetadata.getAnnotationAttributes(EnableMongoWebSession.class.getName()));
this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds");
if (attributes != null) {
this.maxInactiveIntervalInSeconds = attributes.getNumber("maxInactiveIntervalInSeconds");
} else {
this.maxInactiveIntervalInSeconds = ReactiveMongoOperationsSessionRepository.DEFAULT_INACTIVE_INTERVAL;
}
String collectionNameValue = attributes.getString("collectionName");
String collectionNameValue = attributes != null ? attributes.getString("collectionName") : "";
if (StringUtils.hasText(collectionNameValue)) {
this.collectionName = this.embeddedValueResolver.resolveStringValue(collectionNameValue);
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2019 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.
*/
/**
* @author Greg Turnquist
*/
@NonNullApi
package org.springframework.session.data.mongo.config.annotation.web.reactive;
import org.springframework.lang.NonNullApi;

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2019 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.
*/
/**
* @author Greg Turnquist
*/
@NonNullApi
package org.springframework.session.data.mongo;
import org.springframework.lang.NonNullApi;

View File

@@ -22,6 +22,7 @@ import java.time.Duration;
import org.bson.Document;
import org.junit.Test;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.session.FindByIndexNameSessionRepository;
@@ -125,11 +126,13 @@ public abstract class AbstractMongoSessionConverterTest {
assertThat(convertedSession.getMaxInactiveInterval()).isEqualTo(Duration.ofMinutes(30));
}
@Nullable
MongoSession convertToSession(DBObject session) {
return (MongoSession) getMongoSessionConverter().convert(session, TypeDescriptor.valueOf(DBObject.class),
TypeDescriptor.valueOf(MongoSession.class));
}
@Nullable
DBObject convertToDBObject(MongoSession session) {
return (DBObject) getMongoSessionConverter().convert(session, TypeDescriptor.valueOf(MongoSession.class),
TypeDescriptor.valueOf(DBObject.class));

View File

@@ -25,6 +25,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.core.serializer.DefaultDeserializer;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.session.data.mongo.AbstractMongoSessionConverter;
import org.springframework.session.data.mongo.Assert;
import org.springframework.session.data.mongo.JdkMongoSessionConverter;
import org.springframework.util.ReflectionUtils;
@@ -43,7 +44,7 @@ public abstract class AbstractClassLoaderTest<T> extends AbstractITest {
public void verifyContainerClassLoaderLoadedIntoConverter() {
Field mongoSessionConverterField = ReflectionUtils.findField(sessionRepository.getClass(), "mongoSessionConverter");
ReflectionUtils.makeAccessible(mongoSessionConverterField);
ReflectionUtils.makeAccessible(Assert.requireNonNull(mongoSessionConverterField, "mongoSessionConverter must not be null!"));
AbstractMongoSessionConverter sessionConverter = (AbstractMongoSessionConverter) ReflectionUtils
.getField(mongoSessionConverterField, this.sessionRepository);
@@ -63,7 +64,7 @@ public abstract class AbstractClassLoaderTest<T> extends AbstractITest {
private static Object extractField(Class<?> clazz, String fieldName, Object obj) {
Field field = ReflectionUtils.findField(clazz, fieldName);
ReflectionUtils.makeAccessible(field);
ReflectionUtils.makeAccessible(Assert.requireNonNull(field, fieldName + " must not be null!"));
return ReflectionUtils.getField(field, obj);
}

View File

@@ -60,7 +60,7 @@ abstract public class AbstractMongoRepositoryITest extends AbstractITest {
@Autowired protected MongoOperationsSessionRepository repository;
@Test
public void saves() throws InterruptedException {
public void saves() {
String username = "saves-" + System.currentTimeMillis();

View File

@@ -24,8 +24,8 @@ import org.springframework.session.events.AbstractSessionEvent;
public class SessionEventRegistry implements ApplicationListener<AbstractSessionEvent> {
private Map<String, AbstractSessionEvent> events = new HashMap<String, AbstractSessionEvent>();
private Map<String, Object> locks = new HashMap<String, Object>();
private Map<String, AbstractSessionEvent> events = new HashMap<>();
private Map<String, Object> locks = new HashMap<>();
public void onApplicationEvent(AbstractSessionEvent event) {
@@ -67,12 +67,7 @@ public class SessionEventRegistry implements ApplicationListener<AbstractSession
private Object getLock(String sessionId) {
synchronized (this.locks) {
Object lock = this.locks.get(sessionId);
if (lock == null) {
lock = new Object();
this.locks.put(sessionId, lock);
}
return lock;
return this.locks.computeIfAbsent(sessionId, k -> new Object());
}
}
}