Skip to content
This repository was archived by the owner on Feb 7, 2018. It is now read-only.

1. Serialization/deserialization happens in the sessionStore, the utility class only handles the DB operations. 2. SessionTableAttributes was completely removed 3. ExpiredSessionReaper was completely removed 4. The serialization/deserialization happens with Tomcat's own methods. 5. The DB structure was simplified. Only a key (sessionID) and the serialized session data are stored. (Tomcat's reaper needs no more, it checks the expiration date in the deserialized session object) 6 A DB synchronization added to the keys() method (It refresh the keys in each hour from the DB). #19

Merged
merged 1 commit into from
Apr 2, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<artifactId>aws-dynamodb-session-tomcat</artifactId>
<packaging>jar</packaging>
<name>Amazon DynamoDB Session Manager for Tomcat</name>
<version>1.0.2</version>
<version>1.2</version>
<description>The Amazon DynamoDB Session Manager for Tomcat provides a custom session manager for Tomcat 7 that stores session data in Amazon DynamoDB, Amazon's fully managed NoSQL database service.</description>
<url>https://aws.amazon.com/java</url>

Expand Down Expand Up @@ -42,7 +42,7 @@
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>7.0.42</version>
<version>7.0.47</version>
</dependency>
</dependencies>

Expand All @@ -64,8 +64,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3</version>
<configuration>
<source>1.5</source>
<target>1.5</target>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class DynamoDBSessionManager extends PersistentManagerBase {
private static final String DEFAULT_TABLE_NAME = "Tomcat_SessionState";

private static final String name = "AmazonDynamoDBSessionManager";
private static final String info = name + "/1.0";
private static final String info = name + "/2.0";

private String regionId = "us-east-1";
private String endpoint;
Expand All @@ -53,8 +53,6 @@ public class DynamoDBSessionManager extends PersistentManagerBase {

private final DynamoDBSessionStore dynamoSessionStore;

private ExpiredSessionReaper expiredSessionReaper;

private static Log logger;


Expand Down Expand Up @@ -143,13 +141,11 @@ protected void initInternal() throws LifecycleException {
dynamoSessionStore.setDynamoClient(dynamo);
dynamoSessionStore.setSessionTableName(this.tableName);

expiredSessionReaper = new ExpiredSessionReaper(dynamo, tableName, this.maxInactiveInterval);
}

@Override
protected synchronized void stopInternal() throws LifecycleException {
super.stopInternal();
if (expiredSessionReaper != null) expiredSessionReaper.shutdown();
}

private void initDynamoTable(AmazonDynamoDBClient dynamo) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,28 @@
*/
package com.amazonaws.services.dynamodb.sessionmanager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.List;
import java.util.Set;

import org.apache.catalina.Container;
import org.apache.catalina.Loader;
import org.apache.catalina.Session;
import org.apache.catalina.session.StandardSession;
import org.apache.catalina.session.StoreBase;
import org.apache.catalina.util.CustomObjectInputStream;

import com.amazonaws.services.dynamodb.sessionmanager.util.DynamoUtils;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest;
import com.amazonaws.services.dynamodbv2.model.TableDescription;

Expand All @@ -40,118 +45,173 @@
*/
public class DynamoDBSessionStore extends StoreBase {

private static final String name = "AmazonDynamoDBSessionStore";
private static final String info = name + "/1.0";

private AmazonDynamoDBClient dynamo;
private String sessionTableName;

private Set<String> keys = Collections.synchronizedSet(new HashSet<String>());


@Override
public String getInfo() {
return info;
}

@Override
public String getStoreName() {
return name;
}

public void setDynamoClient(AmazonDynamoDBClient dynamo) {
this.dynamo = dynamo;
}

public void setSessionTableName(String tableName) {
this.sessionTableName = tableName;
}


@Override
public void clear() throws IOException {
final Set<String> keysCopy = new HashSet<String>();
keysCopy.addAll(keys);

new Thread("dynamodb-session-manager-clear") {
@Override
public void run() {
for (String sessionId : keysCopy) {
DynamoUtils.deleteSession(dynamo, sessionTableName, sessionId);
}
}
}.start();

keys.clear();
}

@Override
public int getSize() throws IOException {
// The item count from describeTable is updated every ~6 hours
TableDescription table = dynamo.describeTable(new DescribeTableRequest().withTableName(sessionTableName)).getTable();
long itemCount = table.getItemCount();

return (int)itemCount;
}

@Override
public String[] keys() throws IOException {
return keys.toArray(new String[0]);
}

@Override
public Session load(String id) throws ClassNotFoundException, IOException {
Map<String, AttributeValue> item = DynamoUtils.loadItemBySessionId(dynamo, sessionTableName, id);
if (item == null || !item.containsKey(SessionTableAttributes.SESSION_ID_KEY) || !item.containsKey(SessionTableAttributes.SESSION_DATA_ATTRIBUTE)) {
DynamoDBSessionManager.warn("Unable to load session attributes for session " + id);
return null;
}


Session session = getManager().createSession(id);
session.setCreationTime(Long.parseLong(item.get(SessionTableAttributes.CREATED_AT_ATTRIBUTE).getN()));


ByteBuffer byteBuffer = item.get(SessionTableAttributes.SESSION_DATA_ATTRIBUTE).getB();
ByteArrayInputStream inputStream = new ByteArrayInputStream(byteBuffer.array());

Object readObject;
CustomObjectInputStream objectInputStream = null;
try {
Container webapp = getManager().getContainer();
objectInputStream = new CustomObjectInputStream(inputStream, webapp.getLoader().getClassLoader());

readObject = objectInputStream.readObject();
} finally {
try { objectInputStream.close(); } catch (Exception e) {}
}

if (readObject instanceof Map<?, ?>) {
Map<String, Object> sessionAttributeMap = (Map<String, Object>)readObject;

for (String s : sessionAttributeMap.keySet()) {
((StandardSession)session).setAttribute(s, sessionAttributeMap.get(s));
}
} else {
throw new RuntimeException("Error: Unable to unmarshall session attributes from DynamoDB store");
}


keys.add(id);
manager.add(session);

return session;
}

@Override
public void save(Session session) throws IOException {
DynamoUtils.storeSession(dynamo, sessionTableName, session);
keys.add(session.getId());
}

@Override
public void remove(String id) throws IOException {
DynamoUtils.deleteSession(dynamo, sessionTableName, id);
keys.remove(id);
}
private static final String name = "AmazonDynamoDBSessionStore";
private static final String info = name + "/1.0";

private AmazonDynamoDBClient dynamo;
private String sessionTableName;

private Set<String> keys = Collections.synchronizedSet(new HashSet<String>());
private long keysTimestamp=0;

@Override
public String getInfo() {
return info;
}

@Override
public String getStoreName() {
return name;
}

public void setDynamoClient(AmazonDynamoDBClient dynamo) {
this.dynamo = dynamo;
}

public void setSessionTableName(String tableName) {
this.sessionTableName = tableName;
}

@Override
public void clear() throws IOException {
final Set<String> keysCopy = new HashSet<String>();
keysCopy.addAll(keys);

new Thread("dynamodb-session-manager-clear") {
@Override
public void run() {
for (String sessionId : keysCopy) {
remove(sessionId);
}
}
}.start();

}

@Override
public int getSize() throws IOException {
TableDescription table = dynamo.describeTable(new DescribeTableRequest().withTableName(sessionTableName))
.getTable();
long itemCount = table.getItemCount();

return (int) itemCount;
}

@Override
public String[] keys() throws IOException {
// refresh the keys stored in memory in every hour.
if(keysTimestamp<System.currentTimeMillis()-1000L*60*60) {
// Other instances can also add or remove sessions, so we have to synchronise the keys set with the DB sometimes
List<String> list=DynamoUtils.loadKeys(dynamo, sessionTableName);
keys.clear();
keys.addAll(list);
keysTimestamp=System.currentTimeMillis();
}

return keys.toArray(new String[0]);

}

@Override
public Session load(String id) throws ClassNotFoundException, IOException {

ByteBuffer byteBuffer = DynamoUtils.loadItemBySessionId(dynamo, sessionTableName, id);
if (byteBuffer == null) {
keys.remove(id);
return (null);
}

if (manager.getContainer().getLogger().isDebugEnabled()) {
manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".loading", id, sessionTableName));
}

ByteArrayInputStream fis = null;
BufferedInputStream bis = null;
ObjectInputStream ois = null;
Loader loader = null;
ClassLoader classLoader = null;
try {
fis = new ByteArrayInputStream(byteBuffer.array());
bis = new BufferedInputStream(fis);
Container container = manager.getContainer();
if (container != null) {
loader = container.getLoader();
}
if (loader != null) {
classLoader = loader.getClassLoader();
}
if (classLoader != null) {
ois = new CustomObjectInputStream(bis, classLoader);
} else {
ois = new ObjectInputStream(bis);
}
} catch (Exception e) {
if (bis != null) {
try {
bis.close();
} catch (IOException f) {
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException f) {
}
}
throw e;
}

try {
StandardSession session = (StandardSession) manager.createEmptySession();
session.readObjectData(ois);
session.setManager(manager);
keys.add(id);
return (session);
} finally {
try {
ois.close();
} catch (IOException f) {
}
}
}

@Override
public void save(Session session) throws IOException {

String id = session.getIdInternal();

if (manager.getContainer().getLogger().isDebugEnabled()) {
manager.getContainer().getLogger()
.debug(sm.getString(getStoreName() + ".saving", id, sessionTableName));
}

ByteArrayOutputStream fos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new BufferedOutputStream(fos));
} catch (IOException e) {
try {
fos.close();
} catch (IOException f) {
}
throw e;
}

try {
((StandardSession) session).writeObjectData(oos);
} finally {
oos.close();
}
DynamoUtils.storeSession(dynamo, sessionTableName, id, ByteBuffer.wrap(fos.toByteArray()));
keys.add(id);
}

@Override
public void remove(String id) {
if (manager.getContainer().getLogger().isDebugEnabled()) {
manager.getContainer().getLogger().debug(sm.getString(getStoreName() + ".removing", id, sessionTableName));
}
DynamoUtils.deleteSession(dynamo, sessionTableName, id);
keys.remove(id);
}
}
Loading