Code cleanup

pull/15/head
Ranjith Manickam 2018-07-09 18:12:27 +05:30
parent 6a65b99e24
commit 6aff279fbd
12 changed files with 1109 additions and 1112 deletions

View File

@ -11,10 +11,7 @@ import java.security.MessageDigest;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.apache.catalina.util.CustomObjectInputStream; import org.apache.catalina.util.CustomObjectInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/** /**
* Tomcat clustering with Redis data-cache implementation. * Tomcat clustering with Redis data-cache implementation.
@ -28,12 +25,8 @@ public class SerializationUtil {
private ClassLoader loader; private ClassLoader loader;
private Log log = LogFactory.getLog(SerializationUtil.class);
/** /**
* To set class loader * To set class loader
*
* @param loader
*/ */
public void setClassLoader(ClassLoader loader) { public void setClassLoader(ClassLoader loader) {
this.loader = loader; this.loader = loader;
@ -41,48 +34,40 @@ public class SerializationUtil {
/** /**
* To get session attributes hash code * To get session attributes hash code
*
* @param session
* @return
* @throws IOException
*/ */
public byte[] getSessionAttributesHashCode(Session session) throws IOException { public byte[] getSessionAttributesHashCode(Session session) throws IOException {
byte[] serialized = null; byte[] serialized;
Map<String, Object> attributes = new HashMap<String, Object>(); Map<String, Object> attributes = new HashMap<>();
for (Enumeration<String> enumerator = session.getAttributeNames(); enumerator.hasMoreElements();) { for (Enumeration<String> enumerator = session.getAttributeNames();
enumerator.hasMoreElements(); ) {
String key = enumerator.nextElement(); String key = enumerator.nextElement();
attributes.put(key, session.getAttribute(key)); attributes.put(key, session.getAttribute(key));
} }
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));) { ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos))) {
oos.writeUnshared(attributes); oos.writeUnshared(attributes);
oos.flush(); oos.flush();
serialized = bos.toByteArray(); serialized = bos.toByteArray();
} }
MessageDigest digester = null; MessageDigest digester;
try { try {
digester = MessageDigest.getInstance("MD5"); digester = MessageDigest.getInstance("MD5");
} catch (Exception ex) { } catch (Exception ex) {
log.error("Unable to get MessageDigest instance for MD5", ex); throw new RuntimeException("Unable to get MessageDigest instance for MD5", ex);
} }
return digester.digest(serialized); return digester.digest(serialized);
} }
/** /**
* To serialize session object * To serialize session object
*
* @param session
* @param metadata
* @return
* @throws IOException
*/ */
public byte[] serializeSessionData(Session session, SessionMetadata metadata) throws IOException { public byte[] serializeSessionData(Session session, SessionMetadata metadata) throws IOException {
byte[] serialized = null; byte[] serialized;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));) { ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos))) {
oos.writeObject(metadata); oos.writeObject(metadata);
session.writeObjectData(oos); session.writeObjectData(oos);
oos.flush(); oos.flush();
@ -93,17 +78,11 @@ public class SerializationUtil {
/** /**
* To de-serialize session object * To de-serialize session object
*
* @param data
* @param session
* @param metadata
* @throws IOException
* @throws ClassNotFoundException
*/ */
public void deserializeSessionData(byte[] data, Session session, SessionMetadata metadata) public void deserializeSessionData(byte[] data, Session session, SessionMetadata metadata)
throws IOException, ClassNotFoundException { throws IOException, ClassNotFoundException {
try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data)); try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data));
ObjectInputStream ois = new CustomObjectInputStream(bis, this.loader);) { ObjectInputStream ois = new CustomObjectInputStream(bis, this.loader)) {
SessionMetadata serializedMetadata = (SessionMetadata) ois.readObject(); SessionMetadata serializedMetadata = (SessionMetadata) ois.readObject();
metadata.copyFieldsFrom(serializedMetadata); metadata.copyFieldsFrom(serializedMetadata);
session.readObjectData(ois); session.readObjectData(ois);

View File

@ -59,13 +59,17 @@ public class Session extends StandardSession {
return this.changedAttributes; return this.changedAttributes;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void setAttribute(String key, Object value) { public void setAttribute(String key, Object value) {
if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) { if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) {
@ -79,7 +83,8 @@ public class Session extends StandardSession {
if ((value != null || oldValue != null) if ((value != null || oldValue != null)
&& (value == null && oldValue != null || oldValue == null && value != null && (value == null && oldValue != null || oldValue == null && value != null
|| !value.getClass().isInstance(oldValue) || !value.equals(oldValue))) { || !value.getClass().isInstance(oldValue) || !value.equals(oldValue))) {
if (this.manager instanceof SessionManager && ((SessionManager) this.manager).getSaveOnChange()) { if (this.manager instanceof SessionManager && ((SessionManager) this.manager)
.getSaveOnChange()) {
((SessionManager) this.manager).save(this, true); ((SessionManager) this.manager).save(this, true);
} else { } else {
this.changedAttributes.put(key, value); this.changedAttributes.put(key, value);
@ -87,51 +92,66 @@ public class Session extends StandardSession {
} }
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Object getAttribute(String name) { public Object getAttribute(String name) {
return super.getAttribute(name); return super.getAttribute(name);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Enumeration<String> getAttributeNames() { public Enumeration<String> getAttributeNames() {
return super.getAttributeNames(); return super.getAttributeNames();
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void removeAttribute(String name) { public void removeAttribute(String name) {
super.removeAttribute(name); super.removeAttribute(name);
if (this.manager instanceof SessionManager && ((SessionManager) this.manager).getSaveOnChange()) { if (this.manager instanceof SessionManager && ((SessionManager) this.manager)
.getSaveOnChange()) {
((SessionManager) this.manager).save(this, true); ((SessionManager) this.manager).save(this, true);
} else { } else {
this.dirty = true; this.dirty = true;
} }
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void setPrincipal(Principal principal) { public void setPrincipal(Principal principal) {
super.setPrincipal(principal); super.setPrincipal(principal);
this.dirty = true; this.dirty = true;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void writeObjectData(ObjectOutputStream out) throws IOException { public void writeObjectData(ObjectOutputStream out) throws IOException {
super.writeObjectData(out); super.writeObjectData(out);
out.writeLong(this.getCreationTime()); out.writeLong(this.getCreationTime());
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void readObjectData(ObjectInputStream in) throws IOException, ClassNotFoundException { public void readObjectData(ObjectInputStream in) throws IOException, ClassNotFoundException {
super.readObjectData(in); super.readObjectData(in);
this.setCreationTime(in.readLong()); this.setCreationTime(in.readLong());
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void invalidate() { public void invalidate() {
super.invalidate(); super.invalidate();

View File

@ -8,11 +8,11 @@ package tomcat.request.session;
* @author Ranjith Manickam * @author Ranjith Manickam
* @since 2.0 * @since 2.0
*/ */
public class SessionConstants { public interface SessionConstants {
public static final byte[] NULL_SESSION = "null".getBytes(); byte[] NULL_SESSION = "null".getBytes();
public static final String CATALINA_BASE = "catalina.base"; String CATALINA_BASE = "catalina.base";
public static final String CONF = "conf"; String CONF = "conf";
} }

View File

@ -20,8 +20,6 @@ public class SessionContext {
/** /**
* To get session id * To get session id
*
* @return
*/ */
public String getId() { public String getId() {
return id; return id;
@ -29,8 +27,6 @@ public class SessionContext {
/** /**
* To set session id * To set session id
*
* @param id
*/ */
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
@ -38,8 +34,6 @@ public class SessionContext {
/** /**
* To get session * To get session
*
* @return
*/ */
public Session getSession() { public Session getSession() {
return session; return session;
@ -47,8 +41,6 @@ public class SessionContext {
/** /**
* To set session * To set session
*
* @param session
*/ */
public void setSession(Session session) { public void setSession(Session session) {
this.session = session; this.session = session;
@ -56,8 +48,6 @@ public class SessionContext {
/** /**
* To check session is persisted * To check session is persisted
*
* @return
*/ */
public boolean isPersisted() { public boolean isPersisted() {
return persisted; return persisted;
@ -65,8 +55,6 @@ public class SessionContext {
/** /**
* To set session persisted * To set session persisted
*
* @param persisted
*/ */
public void setPersisted(boolean persisted) { public void setPersisted(boolean persisted) {
this.persisted = persisted; this.persisted = persisted;
@ -74,8 +62,6 @@ public class SessionContext {
/** /**
* To get session meta-data * To get session meta-data
*
* @return
*/ */
public SessionMetadata getMetadata() { public SessionMetadata getMetadata() {
return metadata; return metadata;
@ -83,14 +69,14 @@ public class SessionContext {
/** /**
* To set session meta-data * To set session meta-data
*
* @param metadata
*/ */
public void setMetadata(SessionMetadata metadata) { public void setMetadata(SessionMetadata metadata) {
this.metadata = metadata; this.metadata = metadata;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public String toString() { public String toString() {
return "SessionContext [id=" + id + "]"; return "SessionContext [id=" + id + "]";

View File

@ -8,8 +8,7 @@ import java.io.Serializable;
/** /**
* Tomcat clustering with Redis data-cache implementation. * Tomcat clustering with Redis data-cache implementation.
* *
* This class is uses to store and retrieve the HTTP request session object * This class is uses to store and retrieve the HTTP request session object meta-data.
* meta-data.
* *
* @author Ranjith Manickam * @author Ranjith Manickam
* @since 2.0 * @since 2.0
@ -26,8 +25,6 @@ public class SessionMetadata implements Serializable {
/** /**
* To get session meta-data hash * To get session meta-data hash
*
* @return
*/ */
public byte[] getAttributesHash() { public byte[] getAttributesHash() {
return this.attributesHash; return this.attributesHash;
@ -35,8 +32,6 @@ public class SessionMetadata implements Serializable {
/** /**
* To set session meta-data hash * To set session meta-data hash
*
* @param attributesHash
*/ */
public void setAttributesHash(byte[] attributesHash) { public void setAttributesHash(byte[] attributesHash) {
this.attributesHash = attributesHash; this.attributesHash = attributesHash;
@ -44,8 +39,6 @@ public class SessionMetadata implements Serializable {
/** /**
* To copy session meta-data * To copy session meta-data
*
* @param metadata
*/ */
public void copyFieldsFrom(SessionMetadata metadata) { public void copyFieldsFrom(SessionMetadata metadata) {
this.setAttributesHash(metadata.getAttributesHash()); this.setAttributesHash(metadata.getAttributesHash());
@ -53,9 +46,6 @@ public class SessionMetadata implements Serializable {
/** /**
* To write session meta-data to output stream * To write session meta-data to output stream
*
* @param out
* @throws IOException
*/ */
private void writeObject(ObjectOutputStream out) throws IOException { private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(this.attributesHash.length); out.writeInt(this.attributesHash.length);
@ -64,10 +54,6 @@ public class SessionMetadata implements Serializable {
/** /**
* To read session meta-data from input stream * To read session meta-data from input stream
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/ */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
int hashLength = in.readInt(); int hashLength = in.readInt();

View File

@ -12,10 +12,6 @@ public interface DataCache {
/** /**
* To set value in data-cache * To set value in data-cache
*
* @param key
* @param value
* @return
*/ */
byte[] set(String key, byte[] value); byte[] set(String key, byte[] value);
@ -23,35 +19,21 @@ public interface DataCache {
* To set value if key not exists in data-cache * To set value if key not exists in data-cache
* *
* Returns If key exists = 0 else 1 * Returns If key exists = 0 else 1
*
* @param key
* @param value
* @return
*/ */
Long setnx(String key, byte[] value); Long setnx(String key, byte[] value);
/** /**
* To expire the value based on key in data-cache * To expire the value based on key in data-cache
*
* @param key
* @param seconds
* @return
*/ */
Long expire(String key, int seconds); Long expire(String key, int seconds);
/** /**
* To get the value based on key from data-cache * To get the value based on key from data-cache
*
* @param key
* @return
*/ */
byte[] get(String key); byte[] get(String key);
/** /**
* To delete the value based on key from data-cache * To delete the value based on key from data-cache
*
* @param key
* @return
*/ */
Long delete(String key); Long delete(String key);

View File

@ -25,12 +25,14 @@ class RedisCacheUtil implements DataCache {
private Log log = LogFactory.getLog(RedisCacheUtil.class); private Log log = LogFactory.getLog(RedisCacheUtil.class);
public RedisCacheUtil(String host, int port, String password, int database, int timeout, RedisCacheUtil(String host, int port, String password, int database, int timeout,
JedisPoolConfig poolConfig) { JedisPoolConfig poolConfig) {
pool = new JedisPool(poolConfig, host, port, timeout, password, database); pool = new JedisPool(poolConfig, host, port, timeout, password, database);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public byte[] set(String key, byte[] value) { public byte[] set(String key, byte[] value) {
int tries = 0; int tries = 0;
@ -45,14 +47,17 @@ class RedisCacheUtil implements DataCache {
sucess = true; sucess = true;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries); log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) if (tries == NUM_RETRIES) {
throw ex; throw ex;
} }
}
} while (!sucess && tries <= NUM_RETRIES); } while (!sucess && tries <= NUM_RETRIES);
return (retVal != null) ? retVal.getBytes() : null; return (retVal != null) ? retVal.getBytes() : null;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long setnx(String key, byte[] value) { public Long setnx(String key, byte[] value) {
int tries = 0; int tries = 0;
@ -67,14 +72,17 @@ class RedisCacheUtil implements DataCache {
sucess = true; sucess = true;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries); log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) if (tries == NUM_RETRIES) {
throw ex; throw ex;
} }
}
} while (!sucess && tries <= NUM_RETRIES); } while (!sucess && tries <= NUM_RETRIES);
return retVal; return retVal;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long expire(String key, int seconds) { public Long expire(String key, int seconds) {
int tries = 0; int tries = 0;
@ -89,14 +97,17 @@ class RedisCacheUtil implements DataCache {
sucess = true; sucess = true;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries); log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) if (tries == NUM_RETRIES) {
throw ex; throw ex;
} }
}
} while (!sucess && tries <= NUM_RETRIES); } while (!sucess && tries <= NUM_RETRIES);
return retVal; return retVal;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public byte[] get(String key) { public byte[] get(String key) {
int tries = 0; int tries = 0;
@ -111,14 +122,17 @@ class RedisCacheUtil implements DataCache {
sucess = true; sucess = true;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries); log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) if (tries == NUM_RETRIES) {
throw ex; throw ex;
} }
}
} while (!sucess && tries <= NUM_RETRIES); } while (!sucess && tries <= NUM_RETRIES);
return retVal; return retVal;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long delete(String key) { public Long delete(String key) {
int tries = 0; int tries = 0;
@ -133,9 +147,10 @@ class RedisCacheUtil implements DataCache {
sucess = true; sucess = true;
} catch (JedisConnectionException ex) { } catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries); log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) if (tries == NUM_RETRIES) {
throw ex; throw ex;
} }
}
} while (!sucess && tries <= NUM_RETRIES); } while (!sucess && tries <= NUM_RETRIES);
return retVal; return retVal;
} }

View File

@ -30,11 +30,15 @@ class RedisClusterCacheUtil implements DataCache {
private Log log = LogFactory.getLog(RedisClusterCacheUtil.class); private Log log = LogFactory.getLog(RedisClusterCacheUtil.class);
public RedisClusterCacheUtil(Set<HostAndPort> nodes, String password, int timeout, JedisPoolConfig poolConfig) { RedisClusterCacheUtil(Set<HostAndPort> nodes, String password, int timeout,
cluster = new JedisCluster(nodes, timeout, Protocol.DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, password, poolConfig); JedisPoolConfig poolConfig) {
cluster = new JedisCluster(nodes, timeout, Protocol.DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS,
password, poolConfig);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public byte[] set(String key, byte[] value) { public byte[] set(String key, byte[] value) {
int tries = 0; int tries = 0;
@ -56,7 +60,9 @@ class RedisClusterCacheUtil implements DataCache {
return (retVal != null) ? retVal.getBytes() : null; return (retVal != null) ? retVal.getBytes() : null;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long setnx(String key, byte[] value) { public Long setnx(String key, byte[] value) {
int tries = 0; int tries = 0;
@ -78,7 +84,9 @@ class RedisClusterCacheUtil implements DataCache {
return retVal; return retVal;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long expire(String key, int seconds) { public Long expire(String key, int seconds) {
int tries = 0; int tries = 0;
@ -100,7 +108,9 @@ class RedisClusterCacheUtil implements DataCache {
return retVal; return retVal;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public byte[] get(String key) { public byte[] get(String key) {
int tries = 0; int tries = 0;
@ -122,7 +132,9 @@ class RedisClusterCacheUtil implements DataCache {
return retVal; return retVal;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long delete(String key) { public Long delete(String key) {
int tries = 0; int tries = 0;

View File

@ -11,35 +11,35 @@ package tomcat.request.session.data.cache.impl;
interface RedisConstants { interface RedisConstants {
// redis properties file name // redis properties file name
final String PROPERTIES_FILE = "redis-data-cache.properties"; String PROPERTIES_FILE = "redis-data-cache.properties";
// redis properties // redis properties
final String HOSTS = "redis.hosts"; String HOSTS = "redis.hosts";
final String CLUSTER_ENABLED = "redis.cluster.enabled"; String CLUSTER_ENABLED = "redis.cluster.enabled";
final String MAX_ACTIVE = "redis.max.active"; String MAX_ACTIVE = "redis.max.active";
final String TEST_ONBORROW = "redis.test.onBorrow"; String TEST_ONBORROW = "redis.test.onBorrow";
final String TEST_ONRETURN = "redis.test.onReturn"; String TEST_ONRETURN = "redis.test.onReturn";
final String MAX_IDLE = "redis.max.idle"; String MAX_IDLE = "redis.max.idle";
final String MIN_IDLE = "redis.min.idle"; String MIN_IDLE = "redis.min.idle";
final String TEST_WHILEIDLE = "redis.test.whileIdle"; String TEST_WHILEIDLE = "redis.test.whileIdle";
final String TEST_NUMPEREVICTION = "redis.test.numPerEviction"; String TEST_NUMPEREVICTION = "redis.test.numPerEviction";
final String TIME_BETWEENEVICTION = "redis.time.betweenEviction"; String TIME_BETWEENEVICTION = "redis.time.betweenEviction";
final String PASSWORD = "redis.password"; String PASSWORD = "redis.password";
final String DATABASE = "redis.database"; String DATABASE = "redis.database";
final String TIMEOUT = "redis.timeout"; String TIMEOUT = "redis.timeout";
// redis property default values // redis property default values
final String DEFAULT_MAX_ACTIVE_VALUE = "10"; String DEFAULT_MAX_ACTIVE_VALUE = "10";
final String DEFAULT_TEST_ONBORROW_VALUE = "true"; String DEFAULT_TEST_ONBORROW_VALUE = "true";
final String DEFAULT_TEST_ONRETURN_VALUE = "true"; String DEFAULT_TEST_ONRETURN_VALUE = "true";
final String DEFAULT_MAX_IDLE_VALUE = "5"; String DEFAULT_MAX_IDLE_VALUE = "5";
final String DEFAULT_MIN_IDLE_VALUE = "1"; String DEFAULT_MIN_IDLE_VALUE = "1";
final String DEFAULT_TEST_WHILEIDLE_VALUE = "true"; String DEFAULT_TEST_WHILEIDLE_VALUE = "true";
final String DEFAULT_TEST_NUMPEREVICTION_VALUE = "10"; String DEFAULT_TEST_NUMPEREVICTION_VALUE = "10";
final String DEFAULT_TIME_BETWEENEVICTION_VALUE = "60000"; String DEFAULT_TIME_BETWEENEVICTION_VALUE = "60000";
final String DEFAULT_CLUSTER_ENABLED = "false"; String DEFAULT_CLUSTER_ENABLED = "false";
final String CONN_FAILED_RETRY_MSG = "Jedis connection failed, retrying..."; String CONN_FAILED_RETRY_MSG = "Jedis connection failed, retrying...";
} }

View File

@ -39,31 +39,41 @@ public class RedisDataCache implements DataCache {
initialize(); initialize();
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public byte[] set(String key, byte[] value) { public byte[] set(String key, byte[] value) {
return dataCache.set(key, value); return dataCache.set(key, value);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long setnx(String key, byte[] value) { public Long setnx(String key, byte[] value) {
return dataCache.setnx(key, value); return dataCache.setnx(key, value);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long expire(String key, int seconds) { public Long expire(String key, int seconds) {
return dataCache.expire(key, seconds); return dataCache.expire(key, seconds);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public byte[] get(String key) { public byte[] get(String key) {
return (key != null) ? dataCache.get(key) : null; return (key != null) ? dataCache.get(key) : null;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Long delete(String key) { public Long delete(String key) {
return dataCache.delete(key); return dataCache.delete(key);
@ -71,9 +81,6 @@ public class RedisDataCache implements DataCache {
/** /**
* To parse data-cache key * To parse data-cache key
*
* @param key
* @return
*/ */
public static String parseDataCacheKey(String key) { public static String parseDataCacheKey(String key) {
return key.replaceAll("\\s", "_"); return key.replaceAll("\\s", "_");
@ -81,9 +88,6 @@ public class RedisDataCache implements DataCache {
/** /**
* To initialize the data-cache * To initialize the data-cache
*
* @param properties
* @param filePath
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void initialize() { private void initialize() {
@ -92,67 +96,76 @@ public class RedisDataCache implements DataCache {
} }
Properties properties = loadProperties(); Properties properties = loadProperties();
boolean clusterEnabled = Boolean.valueOf(properties.getProperty(RedisConstants.CLUSTER_ENABLED, RedisConstants.DEFAULT_CLUSTER_ENABLED)); boolean clusterEnabled = Boolean.valueOf(properties
.getProperty(RedisConstants.CLUSTER_ENABLED, RedisConstants.DEFAULT_CLUSTER_ENABLED));
String hosts = properties.getProperty(RedisConstants.HOSTS, Protocol.DEFAULT_HOST.concat(":").concat(String.valueOf(Protocol.DEFAULT_PORT))); String hosts = properties.getProperty(RedisConstants.HOSTS,
Protocol.DEFAULT_HOST.concat(":").concat(String.valueOf(Protocol.DEFAULT_PORT)));
Collection<? extends Serializable> nodes = getJedisNodes(hosts, clusterEnabled); Collection<? extends Serializable> nodes = getJedisNodes(hosts, clusterEnabled);
String password = properties.getProperty(RedisConstants.PASSWORD); String password = properties.getProperty(RedisConstants.PASSWORD);
password = (password != null && !password.isEmpty()) ? password : null; password = (password != null && !password.isEmpty()) ? password : null;
int database = Integer.parseInt(properties.getProperty(RedisConstants.DATABASE, String.valueOf(Protocol.DEFAULT_DATABASE))); int database = Integer.parseInt(
properties.getProperty(RedisConstants.DATABASE, String.valueOf(Protocol.DEFAULT_DATABASE)));
int timeout = Integer.parseInt(properties.getProperty(RedisConstants.TIMEOUT, String.valueOf(Protocol.DEFAULT_TIMEOUT))); int timeout = Integer.parseInt(
properties.getProperty(RedisConstants.TIMEOUT, String.valueOf(Protocol.DEFAULT_TIMEOUT)));
timeout = (timeout < Protocol.DEFAULT_TIMEOUT) ? Protocol.DEFAULT_TIMEOUT : timeout; timeout = (timeout < Protocol.DEFAULT_TIMEOUT) ? Protocol.DEFAULT_TIMEOUT : timeout;
if (clusterEnabled) { if (clusterEnabled) {
dataCache = new RedisClusterCacheUtil((Set<HostAndPort>) nodes, password, timeout, getPoolConfig(properties)); dataCache = new RedisClusterCacheUtil((Set<HostAndPort>) nodes, password, timeout,
getPoolConfig(properties));
} else { } else {
dataCache = new RedisCacheUtil(((List<String>) nodes).get(0), dataCache = new RedisCacheUtil(((List<String>) nodes).get(0),
Integer.parseInt(((List<String>) nodes).get(1)), password, database, timeout, getPoolConfig(properties)); Integer.parseInt(((List<String>) nodes).get(1)), password, database, timeout,
getPoolConfig(properties));
} }
} }
/** /**
* To get jedis pool configuration * To get jedis pool configuration
*
* @param properties
* @return
*/ */
private JedisPoolConfig getPoolConfig(Properties properties) { private JedisPoolConfig getPoolConfig(Properties properties) {
JedisPoolConfig poolConfig = new JedisPoolConfig(); JedisPoolConfig poolConfig = new JedisPoolConfig();
int maxActive = Integer.parseInt(properties.getProperty(RedisConstants.MAX_ACTIVE, RedisConstants.DEFAULT_MAX_ACTIVE_VALUE)); int maxActive = Integer.parseInt(
properties.getProperty(RedisConstants.MAX_ACTIVE, RedisConstants.DEFAULT_MAX_ACTIVE_VALUE));
poolConfig.setMaxTotal(maxActive); poolConfig.setMaxTotal(maxActive);
boolean testOnBorrow = Boolean.parseBoolean(properties.getProperty(RedisConstants.TEST_ONBORROW, RedisConstants.DEFAULT_TEST_ONBORROW_VALUE)); boolean testOnBorrow = Boolean.parseBoolean(properties
.getProperty(RedisConstants.TEST_ONBORROW, RedisConstants.DEFAULT_TEST_ONBORROW_VALUE));
poolConfig.setTestOnBorrow(testOnBorrow); poolConfig.setTestOnBorrow(testOnBorrow);
boolean testOnReturn = Boolean.parseBoolean(properties.getProperty(RedisConstants.TEST_ONRETURN, RedisConstants.DEFAULT_TEST_ONRETURN_VALUE)); boolean testOnReturn = Boolean.parseBoolean(properties
.getProperty(RedisConstants.TEST_ONRETURN, RedisConstants.DEFAULT_TEST_ONRETURN_VALUE));
poolConfig.setTestOnReturn(testOnReturn); poolConfig.setTestOnReturn(testOnReturn);
int maxIdle = Integer.parseInt(properties.getProperty(RedisConstants.MAX_ACTIVE, RedisConstants.DEFAULT_MAX_ACTIVE_VALUE)); int maxIdle = Integer.parseInt(
properties.getProperty(RedisConstants.MAX_ACTIVE, RedisConstants.DEFAULT_MAX_ACTIVE_VALUE));
poolConfig.setMaxIdle(maxIdle); poolConfig.setMaxIdle(maxIdle);
int minIdle = Integer.parseInt(properties.getProperty(RedisConstants.MIN_IDLE, RedisConstants.DEFAULT_MIN_IDLE_VALUE)); int minIdle = Integer.parseInt(
properties.getProperty(RedisConstants.MIN_IDLE, RedisConstants.DEFAULT_MIN_IDLE_VALUE));
poolConfig.setMinIdle(minIdle); poolConfig.setMinIdle(minIdle);
boolean testWhileIdle = Boolean.parseBoolean(properties.getProperty(RedisConstants.TEST_WHILEIDLE, RedisConstants.DEFAULT_TEST_WHILEIDLE_VALUE)); boolean testWhileIdle = Boolean.parseBoolean(properties
.getProperty(RedisConstants.TEST_WHILEIDLE, RedisConstants.DEFAULT_TEST_WHILEIDLE_VALUE));
poolConfig.setTestWhileIdle(testWhileIdle); poolConfig.setTestWhileIdle(testWhileIdle);
int testNumPerEviction = Integer.parseInt(properties.getProperty(RedisConstants.TEST_NUMPEREVICTION, RedisConstants.DEFAULT_TEST_NUMPEREVICTION_VALUE)); int testNumPerEviction = Integer.parseInt(properties
.getProperty(RedisConstants.TEST_NUMPEREVICTION,
RedisConstants.DEFAULT_TEST_NUMPEREVICTION_VALUE));
poolConfig.setNumTestsPerEvictionRun(testNumPerEviction); poolConfig.setNumTestsPerEvictionRun(testNumPerEviction);
long timeBetweenEviction = Long.parseLong(properties.getProperty(RedisConstants.TIME_BETWEENEVICTION, RedisConstants.DEFAULT_TIME_BETWEENEVICTION_VALUE)); long timeBetweenEviction = Long.parseLong(properties
.getProperty(RedisConstants.TIME_BETWEENEVICTION,
RedisConstants.DEFAULT_TIME_BETWEENEVICTION_VALUE));
poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEviction); poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEviction);
return poolConfig; return poolConfig;
} }
/** /**
* To get jedis nodes * To get jedis nodes
*
* @param hosts
* @param clusterEnabled
* @return
*/ */
private Collection<? extends Serializable> getJedisNodes(String hosts, boolean clusterEnabled) { private Collection<? extends Serializable> getJedisNodes(String hosts, boolean clusterEnabled) {
hosts = hosts.replaceAll("\\s", ""); hosts = hosts.replaceAll("\\s", "");
@ -182,15 +195,13 @@ public class RedisDataCache implements DataCache {
/** /**
* To load data-cache properties * To load data-cache properties
*
* @param filePath
* @return
*/ */
private Properties loadProperties() { private Properties loadProperties() {
Properties properties = new Properties(); Properties properties = new Properties();
try { try {
String filePath = System.getProperty(SessionConstants.CATALINA_BASE).concat(File.separator) String filePath = System.getProperty(SessionConstants.CATALINA_BASE).concat(File.separator)
.concat(SessionConstants.CONF).concat(File.separator).concat(RedisConstants.PROPERTIES_FILE); .concat(SessionConstants.CONF).concat(File.separator)
.concat(RedisConstants.PROPERTIES_FILE);
InputStream resourceStream = null; InputStream resourceStream = null;
try { try {
@ -203,8 +214,10 @@ public class RedisDataCache implements DataCache {
} }
properties.load(resourceStream); properties.load(resourceStream);
} finally { } finally {
if (resourceStream != null) {
resourceStream.close(); resourceStream.close();
} }
}
} catch (IOException ex) { } catch (IOException ex) {
log.error("Error while loading task scheduler properties", ex); log.error("Error while loading task scheduler properties", ex);
} }

View File

@ -11,8 +11,8 @@ import org.apache.catalina.valves.ValveBase;
/** /**
* Tomcat clustering with Redis data-cache implementation. * Tomcat clustering with Redis data-cache implementation.
* *
* Valve that implements per-request session persistence. It is intended to be * Valve that implements per-request session persistence. It is intended to be used with non-sticky
* used with non-sticky load-balancers. * load-balancers.
* *
* @author Ranjith Manickam * @author Ranjith Manickam
* @since 2.0 * @since 2.0
@ -23,14 +23,14 @@ public class SessionHandlerValve extends ValveBase {
/** /**
* To set session manager * To set session manager
*
* @param manager
*/ */
public void setSessionManager(SessionManager manager) { public void setSessionManager(SessionManager manager) {
this.manager = manager; this.manager = manager;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void invoke(Request request, Response response) throws IOException, ServletException { public void invoke(Request request, Response response) throws IOException, ServletException {
try { try {

View File

@ -28,8 +28,8 @@ import tomcat.request.session.data.cache.impl.RedisDataCache;
/** /**
* Tomcat clustering with Redis data-cache implementation. * Tomcat clustering with Redis data-cache implementation.
* *
* Manager that implements per-request session persistence. It is intended to be * Manager that implements per-request session persistence. It is intended to be used with
* used with non-sticky load-balancers. * non-sticky load-balancers.
* *
* @author Ranjith Manickam * @author Ranjith Manickam
* @since 2.0 * @since 2.0
@ -63,8 +63,6 @@ public class SessionManager extends ManagerBase implements Lifecycle {
/** /**
* To get session persist policies * To get session persist policies
*
* @return
*/ */
public String getSessionPersistPolicies() { public String getSessionPersistPolicies() {
String policyStr = null; String policyStr = null;
@ -76,8 +74,6 @@ public class SessionManager extends ManagerBase implements Lifecycle {
/** /**
* To set session persist policies * To set session persist policies
*
* @param policyStr
*/ */
public void setSessionPersistPolicies(String policyStr) { public void setSessionPersistPolicies(String policyStr) {
Set<SessionPolicy> policySet = EnumSet.of(SessionPolicy.DEFAULT); Set<SessionPolicy> policySet = EnumSet.of(SessionPolicy.DEFAULT);
@ -89,39 +85,41 @@ public class SessionManager extends ManagerBase implements Lifecycle {
this.sessionPolicy = policySet; this.sessionPolicy = policySet;
} }
/**
* @return
*/
public boolean getSaveOnChange() { public boolean getSaveOnChange() {
return this.sessionPolicy.contains(SessionPolicy.SAVE_ON_CHANGE); return this.sessionPolicy.contains(SessionPolicy.SAVE_ON_CHANGE);
} }
/**
* @return
*/
public boolean getAlwaysSaveAfterRequest() { public boolean getAlwaysSaveAfterRequest() {
return this.sessionPolicy.contains(SessionPolicy.ALWAYS_SAVE_AFTER_REQUEST); return this.sessionPolicy.contains(SessionPolicy.ALWAYS_SAVE_AFTER_REQUEST);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void addLifecycleListener(LifecycleListener listener) { public void addLifecycleListener(LifecycleListener listener) {
super.addLifecycleListener(listener); super.addLifecycleListener(listener);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public LifecycleListener[] findLifecycleListeners() { public LifecycleListener[] findLifecycleListeners() {
return super.findLifecycleListeners(); return super.findLifecycleListeners();
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void removeLifecycleListener(LifecycleListener listener) { public void removeLifecycleListener(LifecycleListener listener) {
super.removeLifecycleListener(listener); super.removeLifecycleListener(listener);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
protected synchronized void startInternal() throws LifecycleException { protected synchronized void startInternal() throws LifecycleException {
super.startInternal(); super.startInternal();
@ -138,8 +136,9 @@ public class SessionManager extends ManagerBase implements Lifecycle {
} }
} }
if (!initializedValve) if (!initializedValve) {
throw new LifecycleException("Session handling valve is not initialized.."); throw new LifecycleException("Session handling valve is not initialized..");
}
initialize(); initialize();
@ -147,25 +146,30 @@ public class SessionManager extends ManagerBase implements Lifecycle {
context.setDistributable(true); context.setDistributable(true);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
protected synchronized void stopInternal() throws LifecycleException { protected synchronized void stopInternal() throws LifecycleException {
super.setState(LifecycleState.STOPPING); super.setState(LifecycleState.STOPPING);
super.stopInternal(); super.stopInternal();
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Session createSession(String sessionId) { public Session createSession(String sessionId) {
if (sessionId != null) { if (sessionId != null) {
sessionId = (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L) ? null : sessionId; sessionId =
(this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L) ? null : sessionId;
} else { } else {
do { do {
sessionId = generateSessionId(); sessionId = generateSessionId();
} while (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L); } while (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L);
} }
Session session = (sessionId != null) ? (Session) createEmptySession() : null; Session session = (sessionId != null) ? createEmptySession() : null;
if (session != null) { if (session != null) {
session.setId(sessionId); session.setId(sessionId);
session.setNew(true); session.setNew(true);
@ -180,7 +184,7 @@ public class SessionManager extends ManagerBase implements Lifecycle {
try { try {
save(session, true); save(session, true);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Error occured while creating session..", ex); log.error("Error occurred while creating session..", ex);
setValues(null, null); setValues(null, null);
session = null; session = null;
} }
@ -188,23 +192,30 @@ public class SessionManager extends ManagerBase implements Lifecycle {
return session; return session;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Session createEmptySession() { public Session createEmptySession() {
return new Session(this); return new Session(this);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void add(org.apache.catalina.Session session) { public void add(org.apache.catalina.Session session) {
save(session, false); save(session, false);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public Session findSession(String sessionId) throws IOException { public Session findSession(String sessionId) throws IOException {
Session session = null; Session session = null;
if (sessionId != null && this.sessionContext.get() != null && sessionId.equals(this.sessionContext.get().getId())) { if (sessionId != null && this.sessionContext.get() != null && sessionId
.equals(this.sessionContext.get().getId())) {
session = this.sessionContext.get().getSession(); session = this.sessionContext.get().getSession();
} else { } else {
byte[] data = this.dataCache.get(sessionId); byte[] data = this.dataCache.get(sessionId);
@ -222,7 +233,7 @@ public class SessionManager extends ManagerBase implements Lifecycle {
} }
try { try {
metadata = new SessionMetadata(); metadata = new SessionMetadata();
Session newSession = (Session) createEmptySession(); Session newSession = createEmptySession();
this.serializer.deserializeSessionData(data, newSession, metadata); this.serializer.deserializeSessionData(data, newSession, metadata);
newSession.setId(sessionId); newSession.setId(sessionId);
@ -235,7 +246,7 @@ public class SessionManager extends ManagerBase implements Lifecycle {
session = newSession; session = newSession;
isPersisted = true; isPersisted = true;
} catch (Exception ex) { } catch (Exception ex) {
log.error("Error occured while de-serializing the session object..", ex); log.error("Error occurred while de-serializing the session object..", ex);
} }
} }
setValues(sessionId, session, isPersisted, metadata); setValues(sessionId, session, isPersisted, metadata);
@ -243,25 +254,33 @@ public class SessionManager extends ManagerBase implements Lifecycle {
return session; return session;
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void remove(org.apache.catalina.Session session) { public void remove(org.apache.catalina.Session session) {
remove(session, false); remove(session, false);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void remove(org.apache.catalina.Session session, boolean update) { public void remove(org.apache.catalina.Session session, boolean update) {
this.dataCache.expire(session.getId(), 10); this.dataCache.expire(session.getId(), 10);
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void load() throws ClassNotFoundException, IOException { public void load() throws ClassNotFoundException, IOException {
// Auto-generated method stub // Auto-generated method stub
} }
/** {@inheritDoc} */ /**
* {@inheritDoc}
*/
@Override @Override
public void unload() throws IOException { public void unload() throws IOException {
// Auto-generated method stub // Auto-generated method stub
@ -276,36 +295,39 @@ public class SessionManager extends ManagerBase implements Lifecycle {
this.serializer = new SerializationUtil(); this.serializer = new SerializationUtil();
Context context = getContextIns(); Context context = getContextIns();
ClassLoader loader = (context != null && context.getLoader() != null) ? context.getLoader().getClassLoader() : null; ClassLoader loader =
(context != null && context.getLoader() != null) ? context.getLoader().getClassLoader()
: null;
this.serializer.setClassLoader(loader); this.serializer.setClassLoader(loader);
} catch (Exception ex) { } catch (Exception ex) {
log.error("Error occured while initializing the session manager..", ex); log.error("Error occurred while initializing the session manager..", ex);
throw ex; throw ex;
} }
} }
/** /**
* To save session object to data-cache * To save session object to data-cache
*
* @param session
* @param forceSave
*/ */
public void save(org.apache.catalina.Session session, boolean forceSave) { public void save(org.apache.catalina.Session session, boolean forceSave) {
try { try {
Boolean isPersisted; Boolean isPersisted;
Session newSession = (Session) session; Session newSession = (Session) session;
byte[] hash = (this.sessionContext.get() != null && this.sessionContext.get().getMetadata() != null) byte[] hash =
(this.sessionContext.get() != null && this.sessionContext.get().getMetadata() != null)
? this.sessionContext.get().getMetadata().getAttributesHash() : null; ? this.sessionContext.get().getMetadata().getAttributesHash() : null;
byte[] currentHash = serializer.getSessionAttributesHashCode(newSession); byte[] currentHash = serializer.getSessionAttributesHashCode(newSession);
if (forceSave || newSession.isDirty() if (forceSave || newSession.isDirty()
|| (isPersisted = (this.sessionContext.get() != null) ? this.sessionContext.get().isPersisted() : null) == null || (isPersisted =
(this.sessionContext.get() != null) ? this.sessionContext.get().isPersisted() : null)
== null
|| !isPersisted || !Arrays.equals(hash, currentHash)) { || !isPersisted || !Arrays.equals(hash, currentHash)) {
SessionMetadata metadata = new SessionMetadata(); SessionMetadata metadata = new SessionMetadata();
metadata.setAttributesHash(currentHash); metadata.setAttributesHash(currentHash);
this.dataCache.set(newSession.getId(), serializer.serializeSessionData(newSession, metadata)); this.dataCache
.set(newSession.getId(), serializer.serializeSessionData(newSession, metadata));
newSession.resetDirtyTracking(); newSession.resetDirtyTracking();
setValues(true, metadata); setValues(true, metadata);
} }
@ -315,47 +337,41 @@ public class SessionManager extends ManagerBase implements Lifecycle {
log.trace("Session [" + newSession.getId() + "] expire in [" + timeout + "] seconds."); log.trace("Session [" + newSession.getId() + "] expire in [" + timeout + "] seconds.");
} catch (IOException ex) { } catch (IOException ex) {
log.error("Error occured while saving the session object in data cache..", ex); log.error("Error occurred while saving the session object in data cache..", ex);
} }
} }
/** /**
* To process post request process * To process post request process
*
* @param request
*/ */
public void afterRequest(Request request) { public void afterRequest(Request request) {
Session session = null; Session session = null;
try { try {
session = (this.sessionContext.get() != null) ? this.sessionContext.get().getSession() : null; session = (this.sessionContext.get() != null) ? this.sessionContext.get().getSession() : null;
if (session != null) { if (session != null) {
if (session.isValid()) if (session.isValid()) {
save(session, getAlwaysSaveAfterRequest()); save(session, getAlwaysSaveAfterRequest());
else } else {
remove(session); remove(session);
log.trace("Session object " + (session.isValid() ? "saved: " : "removed: ") + session.getId()); }
log.trace(
"Session object " + (session.isValid() ? "saved: " : "removed: ") + session.getId());
} }
} catch (Exception ex) { } catch (Exception ex) {
log.error("Error occured while processing post request process..", ex); log.error("Error occurred while processing post request process..", ex);
} finally { } finally {
this.sessionContext.remove(); this.sessionContext.remove();
log.trace("Session removed from ThreadLocal:" + ((session != null) ? session.getIdInternal() : "")); log.trace(
"Session removed from ThreadLocal:" + ((session != null) ? session.getIdInternal() : ""));
} }
} }
/**
* @return
*/
private int getSessionTimeout(Session session) { private int getSessionTimeout(Session session) {
int timeout = getContextIns().getSessionTimeout() * 60; int timeout = getContextIns().getSessionTimeout() * 60;
int sessionTimeout = (session == null) ? 0 : session.getMaxInactiveInterval(); int sessionTimeout = (session == null) ? 0 : session.getMaxInactiveInterval();
return (sessionTimeout < timeout) ? ((timeout < 1800) ? 1800 : timeout) : sessionTimeout; return (sessionTimeout < timeout) ? ((timeout < 1800) ? 1800 : timeout) : sessionTimeout;
} }
/**
* @param sessionId
* @param session
*/
private void setValues(String sessionId, Session session) { private void setValues(String sessionId, Session session) {
if (this.sessionContext.get() == null) { if (this.sessionContext.get() == null) {
this.sessionContext.set(new SessionContext()); this.sessionContext.set(new SessionContext());
@ -364,10 +380,6 @@ public class SessionManager extends ManagerBase implements Lifecycle {
this.sessionContext.get().setSession(session); this.sessionContext.get().setSession(session);
} }
/**
* @param isPersisted
* @param metadata
*/
private void setValues(boolean isPersisted, SessionMetadata metadata) { private void setValues(boolean isPersisted, SessionMetadata metadata) {
if (this.sessionContext.get() == null) { if (this.sessionContext.get() == null) {
this.sessionContext.set(new SessionContext()); this.sessionContext.set(new SessionContext());
@ -376,20 +388,12 @@ public class SessionManager extends ManagerBase implements Lifecycle {
this.sessionContext.get().setPersisted(isPersisted); this.sessionContext.get().setPersisted(isPersisted);
} }
/** private void setValues(String sessionId, Session session, boolean isPersisted,
* @param sessionId SessionMetadata metadata) {
* @param session
* @param isPersisted
* @param metadata
*/
private void setValues(String sessionId, Session session, boolean isPersisted, SessionMetadata metadata) {
setValues(sessionId, session); setValues(sessionId, session);
setValues(isPersisted, metadata); setValues(isPersisted, metadata);
} }
/**
* @return
*/
private Context getContextIns() { private Context getContextIns() {
try { try {
Method method = this.getClass().getSuperclass().getDeclaredMethod("getContext"); Method method = this.getClass().getSuperclass().getDeclaredMethod("getContext");
@ -402,6 +406,6 @@ public class SessionManager extends ManagerBase implements Lifecycle {
log.error("Error in getContext", ex2); log.error("Error in getContext", ex2);
} }
} }
return null; throw new RuntimeException("Error occurred while creating container instance");
} }
} }