You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2017/05/04 00:08:01 UTC
[47/54] geode git commit: Revert session module changes because of
failures
Revert session module changes because of failures
Project: http://git-wip-us.apache.org/repos/asf/geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/geode/commit/8437e65b
Tree: http://git-wip-us.apache.org/repos/asf/geode/tree/8437e65b
Diff: http://git-wip-us.apache.org/repos/asf/geode/diff/8437e65b
Branch: refs/heads/feature/GEODE-2632-11
Commit: 8437e65b86c47573644107d81c6fe35aa4cbda03
Parents: b882d5b
Author: Kirk Lund <kl...@apache.org>
Authored: Wed May 3 15:00:30 2017 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Wed May 3 17:06:24 2017 -0700
----------------------------------------------------------------------
.../session/internal/common/CacheProperty.java | 9 +-
.../internal/filter/GemfireSessionManager.java | 332 ++++++++++---------
.../session/catalina/DeltaSessionManager.java | 238 +++++++------
.../modules/util/CreateRegionFunction.java | 62 ++--
4 files changed, 360 insertions(+), 281 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/geode/blob/8437e65b/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/common/CacheProperty.java
----------------------------------------------------------------------
diff --git a/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/common/CacheProperty.java b/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/common/CacheProperty.java
index aa1a621..fe16fc3 100644
--- a/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/common/CacheProperty.java
+++ b/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/common/CacheProperty.java
@@ -12,6 +12,7 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
+
package org.apache.geode.modules.session.internal.common;
/**
@@ -36,7 +37,7 @@ public enum CacheProperty {
/**
* This parameter can take the following values which match the respective attribute container
* classes
- * <p>
+ * <p/>
* delta_queued : QueuedDeltaSessionAttributes delta_immediate : DeltaSessionAttributes immediate
* : ImmediateSessionAttributes queued : QueuedSessionAttributes
*/
@@ -44,18 +45,18 @@ public enum CacheProperty {
/**
* This parameter can take the following values:
- * <p>
+ * <p/>
* set (default) set_and_get
*/
REPLICATION_TRIGGER(String.class);
- private final Class clazz;
+ Class clazz;
CacheProperty(Class clazz) {
this.clazz = clazz;
}
public Class getClazz() {
- return this.clazz;
+ return clazz;
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/8437e65b/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/filter/GemfireSessionManager.java
----------------------------------------------------------------------
diff --git a/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/filter/GemfireSessionManager.java b/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/filter/GemfireSessionManager.java
index f240a97..20cfeca 100644
--- a/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/filter/GemfireSessionManager.java
+++ b/extensions/geode-modules-session-internal/src/main/java/org/apache/geode/modules/session/internal/filter/GemfireSessionManager.java
@@ -12,35 +12,15 @@
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
-package org.apache.geode.modules.session.internal.filter;
-
-import java.util.EnumMap;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.servlet.FilterConfig;
-import javax.servlet.http.HttpSession;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+package org.apache.geode.modules.session.internal.filter;
import org.apache.geode.cache.CacheClosedException;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.EntryNotFoundException;
-import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.control.ResourceManager;
import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.modules.session.bootstrap.AbstractCache;
import org.apache.geode.modules.session.bootstrap.ClientServerCache;
import org.apache.geode.modules.session.bootstrap.LifecycleTypeAdapter;
@@ -53,8 +33,21 @@ import org.apache.geode.modules.session.internal.filter.attributes.AbstractSessi
import org.apache.geode.modules.session.internal.filter.attributes.DeltaQueuedSessionAttributes;
import org.apache.geode.modules.session.internal.filter.attributes.DeltaSessionAttributes;
import org.apache.geode.modules.session.internal.filter.attributes.ImmediateSessionAttributes;
+import org.apache.geode.modules.session.internal.filter.util.TypeAwareMap;
import org.apache.geode.modules.session.internal.jmx.SessionStatistics;
import org.apache.geode.modules.util.RegionHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+import javax.naming.InitialContext;
+import javax.servlet.FilterConfig;
+import javax.servlet.http.HttpSession;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
/**
* This class implements the session management using a Gemfire distributedCache as a persistent
@@ -62,7 +55,7 @@ import org.apache.geode.modules.util.RegionHelper;
*/
public class GemfireSessionManager implements SessionManager {
- private final Logger logger;
+ private final Logger LOG;
/**
* Prefix of init param string used to set gemfire properties
@@ -102,12 +95,12 @@ public class GemfireSessionManager implements SessionManager {
/**
* Map of wrapping GemFire session id to native session id
*/
- private final Map<String, String> nativeSessionMap = new HashMap<>();
+ private Map<String, String> nativeSessionMap = new HashMap<String, String>();
/**
* MBean for statistics
*/
- private final SessionStatistics sessionStatisticsMBean;
+ private SessionStatistics mbean;
/**
* This CL is used to compare against the class loader of attributes getting pulled out of the
@@ -125,114 +118,138 @@ public class GemfireSessionManager implements SessionManager {
/**
* Set up properties with default values
*/
- private final EnumMap<CacheProperty, Object> properties = createPropertiesEnumMap();
+ private TypeAwareMap<CacheProperty, Object> properties =
+ new TypeAwareMap<CacheProperty, Object>(CacheProperty.class) {
+ {
+ put(CacheProperty.REGION_NAME, RegionHelper.NAME + "_sessions");
+ put(CacheProperty.ENABLE_GATEWAY_DELTA_REPLICATION, Boolean.FALSE);
+ put(CacheProperty.ENABLE_GATEWAY_REPLICATION, Boolean.FALSE);
+ put(CacheProperty.ENABLE_DEBUG_LISTENER, Boolean.FALSE);
+ put(CacheProperty.STATISTICS_NAME, "gemfire_statistics");
+ put(CacheProperty.SESSION_DELTA_POLICY, "delta_queued");
+ put(CacheProperty.REPLICATION_TRIGGER, "set");
+ /**
+ * For REGION_ATTRIBUTES_ID and ENABLE_LOCAL_CACHE the default is different for
+ * ClientServerCache and PeerToPeerCache so those values are set in the relevant
+ * constructors when these properties are passed in to them.
+ */
+ }
+ };
public GemfireSessionManager() {
- this.logger = LoggerFactory.getLogger(GemfireSessionManager.class.getName());
- this.sessionStatisticsMBean = new SessionStatistics();
+ LOG = LoggerFactory.getLogger(GemfireSessionManager.class.getName());
}
+ /**
+ * {@inheritDoc}
+ */
@Override
- public void start(Object config, ClassLoader loader) {
+ public void start(Object conf, ClassLoader loader) {
this.referenceClassLoader = loader;
- FilterConfig filterConfig = (FilterConfig) config;
+ FilterConfig config = (FilterConfig) conf;
- startDistributedSystem(filterConfig);
- initializeSessionCache(filterConfig);
+ startDistributedSystem(config);
+ initializeSessionCache(config);
// Register MBean
- try {
- registerMBean(this.sessionStatisticsMBean);
- } catch (NamingException e) {
- this.logger.warn("Unable to register statistics MBean. Error: {}", e.getMessage(), e);
- }
+ registerMBean();
- if (this.distributedCache.getClass().getClassLoader() == loader) {
- this.isolated = true;
+ if (distributedCache.getClass().getClassLoader() == loader) {
+ isolated = true;
}
- String sessionCookieName = filterConfig.getInitParameter(INIT_PARAM_SESSION_COOKIE_NAME);
+ String sessionCookieName = config.getInitParameter(INIT_PARAM_SESSION_COOKIE_NAME);
if (sessionCookieName != null && !sessionCookieName.isEmpty()) {
this.sessionCookieName = sessionCookieName;
- this.logger.info("Session cookie name set to: {}", this.sessionCookieName);
+ LOG.info("Session cookie name set to: {}", this.sessionCookieName);
}
- this.jvmId = filterConfig.getInitParameter(INIT_PARAM_JVM_ID);
- if (this.jvmId == null || this.jvmId.isEmpty()) {
- this.jvmId = DEFAULT_JVM_ID;
+ jvmId = config.getInitParameter(INIT_PARAM_JVM_ID);
+ if (jvmId == null || jvmId.isEmpty()) {
+ jvmId = DEFAULT_JVM_ID;
}
- this.logger.info("Started GemfireSessionManager (isolated={}, jvmId={})", this.isolated,
- this.jvmId);
+ LOG.info("Started GemfireSessionManager (isolated={}, jvmId={})", isolated, jvmId);
}
+ /**
+ * {@inheritDoc}
+ */
@Override
public void stop() {
- this.isStopping = true;
+ isStopping = true;
- if (this.isolated) {
- if (this.distributedCache != null) {
- this.logger.info("Closing distributed cache - assuming isolated cache");
- this.distributedCache.close();
+ if (isolated) {
+ if (distributedCache != null) {
+ LOG.info("Closing distributed cache - assuming isolated cache");
+ distributedCache.close();
}
} else {
- this.logger.info("Not closing distributed cache - assuming common cache");
+ LOG.info("Not closing distributed cache - assuming common cache");
}
}
+ /**
+ * {@inheritDoc}
+ */
@Override
public HttpSession getSession(String id) {
- GemfireHttpSession session =
- (GemfireHttpSession) this.sessionCache.getOperatingRegion().get(id);
+ GemfireHttpSession session = (GemfireHttpSession) sessionCache.getOperatingRegion().get(id);
if (session != null) {
if (session.justSerialized()) {
session.setManager(this);
- this.logger.debug("Recovered serialized session {} (jvmId={})", id,
- session.getJvmOwnerId());
+ LOG.debug("Recovered serialized session {} (jvmId={})", id, session.getJvmOwnerId());
}
- this.logger.debug("Retrieved session id {}", id);
+ LOG.debug("Retrieved session id {}", id);
} else {
- this.logger.debug("Session id {} not found", id);
+ LOG.debug("Session id {} not found", id);
}
return session;
}
+ /**
+ * {@inheritDoc}
+ */
@Override
public HttpSession wrapSession(HttpSession nativeSession) {
String id = generateId();
GemfireHttpSession session = new GemfireHttpSession(id, nativeSession);
- // Set up the attribute container depending on how things are configured
+ /**
+ * Set up the attribute container depending on how things are configured
+ */
AbstractSessionAttributes attributes;
- if ("delta_queued".equals(this.properties.get(CacheProperty.SESSION_DELTA_POLICY))) {
+ if ("delta_queued".equals(properties.get(CacheProperty.SESSION_DELTA_POLICY))) {
attributes = new DeltaQueuedSessionAttributes();
((DeltaQueuedSessionAttributes) attributes)
- .setReplicationTrigger((String) this.properties.get(CacheProperty.REPLICATION_TRIGGER));
- } else if ("delta_immediate".equals(this.properties.get(CacheProperty.SESSION_DELTA_POLICY))) {
+ .setReplicationTrigger((String) properties.get(CacheProperty.REPLICATION_TRIGGER));
+ } else if ("delta_immediate".equals(properties.get(CacheProperty.SESSION_DELTA_POLICY))) {
attributes = new DeltaSessionAttributes();
- } else if ("immediate".equals(this.properties.get(CacheProperty.SESSION_DELTA_POLICY))) {
+ } else if ("immediate".equals(properties.get(CacheProperty.SESSION_DELTA_POLICY))) {
attributes = new ImmediateSessionAttributes();
} else {
attributes = new DeltaSessionAttributes();
- this.logger.warn("No session delta policy specified - using default of 'delta_immediate'");
+ LOG.warn("No session delta policy specified - using default of 'delta_immediate'");
}
attributes.setSession(session);
- attributes.setJvmOwnerId(this.jvmId);
+ attributes.setJvmOwnerId(jvmId);
session.setManager(this);
session.setAttributes(attributes);
- this.logger.debug("Creating new session {}", id);
- this.sessionCache.getOperatingRegion().put(id, session);
+ LOG.debug("Creating new session {}", id);
+ sessionCache.getOperatingRegion().put(id, session);
- this.sessionStatisticsMBean.incActiveSessions();
+ mbean.incActiveSessions();
return session;
}
- @Override
+ /**
+ * {@inheritDoc}
+ */
public HttpSession getWrappingSession(String nativeId) {
HttpSession session = null;
String gemfireId = getGemfireSessionIdFromNativeId(nativeId);
@@ -243,81 +260,112 @@ public class GemfireSessionManager implements SessionManager {
return session;
}
+ /**
+ * {@inheritDoc}
+ */
@Override
public void destroySession(String id) {
- if (!this.isStopping) {
+ if (!isStopping) {
try {
- GemfireHttpSession session =
- (GemfireHttpSession) this.sessionCache.getOperatingRegion().get(id);
- if (session != null && session.getJvmOwnerId().equals(this.jvmId)) {
- this.logger.debug("Destroying session {}", id);
- this.sessionCache.getOperatingRegion().destroy(id);
- this.sessionStatisticsMBean.decActiveSessions();
+ GemfireHttpSession session = (GemfireHttpSession) sessionCache.getOperatingRegion().get(id);
+ if (session != null && session.getJvmOwnerId().equals(jvmId)) {
+ LOG.debug("Destroying session {}", id);
+ sessionCache.getOperatingRegion().destroy(id);
+ mbean.decActiveSessions();
}
- } catch (EntryNotFoundException ignore) {
+ } catch (EntryNotFoundException nex) {
}
} else {
- if (this.sessionCache.isClientServer()) {
- this.logger.debug("Destroying session {}", id);
+ if (sessionCache.isClientServer()) {
+ LOG.debug("Destroying session {}", id);
try {
- this.sessionCache.getOperatingRegion().localDestroy(id);
- } catch (EntryNotFoundException | CacheClosedException ignore) {
+ sessionCache.getOperatingRegion().localDestroy(id);
+ } catch (EntryNotFoundException nex) {
+ // Ignored
+ } catch (CacheClosedException ccex) {
// Ignored
}
} else {
- GemfireHttpSession session =
- (GemfireHttpSession) this.sessionCache.getOperatingRegion().get(id);
+ GemfireHttpSession session = (GemfireHttpSession) sessionCache.getOperatingRegion().get(id);
if (session != null) {
session.setNativeSession(null);
}
}
}
- synchronized (this.nativeSessionMap) {
- String nativeId = this.nativeSessionMap.remove(id);
- this.logger.debug("destroySession called for {} wrapping {}", id, nativeId);
+ synchronized (nativeSessionMap) {
+ String nativeId = nativeSessionMap.remove(id);
+ LOG.debug("destroySession called for {} wrapping {}", id, nativeId);
}
}
+ /**
+ * {@inheritDoc}
+ */
@Override
public void putSession(HttpSession session) {
- this.sessionCache.getOperatingRegion().put(session.getId(), session);
- this.sessionStatisticsMBean.incRegionUpdates();
- this.nativeSessionMap.put(session.getId(),
+ sessionCache.getOperatingRegion().put(session.getId(), session);
+ mbean.incRegionUpdates();
+ nativeSessionMap.put(session.getId(),
((GemfireHttpSession) session).getNativeSession().getId());
}
@Override
- public String destroyNativeSession(String id) {
- String gemfireSessionId = getGemfireSessionIdFromNativeId(id);
+ public String destroyNativeSession(String nativeId) {
+ String gemfireSessionId = getGemfireSessionIdFromNativeId(nativeId);
if (gemfireSessionId != null) {
destroySession(gemfireSessionId);
}
return gemfireSessionId;
}
- ClassLoader getReferenceClassLoader() {
- return this.referenceClassLoader;
+ public ClassLoader getReferenceClassLoader() {
+ return referenceClassLoader;
+ }
+
+ /**
+ * This method is called when a native session gets destroyed. It will check if the GemFire
+ * session is actually still valid/not expired and will then attach a new, native session.
+ *
+ * @param nativeId the id of the native session
+ * @return the id of the newly attached native session or null if the GemFire session was already
+ * invalid
+ */
+ public String refreshSession(String nativeId) {
+ String gemfireId = getGemfireSessionIdFromNativeId(nativeId);
+ if (gemfireId == null) {
+ return null;
+ }
+
+ GemfireHttpSession session =
+ (GemfireHttpSession) sessionCache.getOperatingRegion().get(gemfireId);
+ if (session.isValid()) {
+
+ }
+
+ return null;
}
- @Override
public String getSessionCookieName() {
- return this.sessionCookieName;
+ return sessionCookieName;
}
- @Override
public String getJvmId() {
- return this.jvmId;
+ return jvmId;
}
+
+ ///////////////////////////////////////////////////////////////////////
+ // Private methods
+
private String getGemfireSessionIdFromNativeId(String nativeId) {
if (nativeId == null) {
return null;
}
- for (Map.Entry<String, String> entry : this.nativeSessionMap.entrySet()) {
- if (nativeId.equals(entry.getValue())) {
- return entry.getKey();
+ for (Map.Entry<String, String> e : nativeSessionMap.entrySet()) {
+ if (nativeId.equals(e.getValue())) {
+ return e.getKey();
}
}
return null;
@@ -325,21 +373,23 @@ public class GemfireSessionManager implements SessionManager {
/**
* Start the underlying distributed system
+ *
+ * @param config
*/
private void startDistributedSystem(FilterConfig config) {
// Get the distributedCache type
final String cacheType = config.getInitParameter(INIT_PARAM_CACHE_TYPE);
if (CACHE_TYPE_CLIENT_SERVER.equals(cacheType)) {
- this.distributedCache = ClientServerCache.getInstance();
+ distributedCache = ClientServerCache.getInstance();
} else if (CACHE_TYPE_PEER_TO_PEER.equals(cacheType)) {
- this.distributedCache = PeerToPeerCache.getInstance();
+ distributedCache = PeerToPeerCache.getInstance();
} else {
- this.logger.error("No 'cache-type' initialization param set. " + "Cache will not be started");
+ LOG.error("No 'cache-type' initialization param set. " + "Cache will not be started");
return;
}
- if (!this.distributedCache.isStarted()) {
- /*
+ if (!distributedCache.isStarted()) {
+ /**
* Process all the init params and see if any apply to the distributed system.
*/
for (Enumeration<String> e = config.getInitParameterNames(); e.hasMoreElements();) {
@@ -349,12 +399,12 @@ public class GemfireSessionManager implements SessionManager {
}
String gemfireProperty = param.substring(GEMFIRE_PROPERTY.length());
- this.logger.info("Setting gemfire property: {} = {}", gemfireProperty,
+ LOG.info("Setting gemfire property: {} = {}", gemfireProperty,
config.getInitParameter(param));
- this.distributedCache.setProperty(gemfireProperty, config.getInitParameter(param));
+ distributedCache.setProperty(gemfireProperty, config.getInitParameter(param));
}
- this.distributedCache.lifecycleEvent(LifecycleTypeAdapter.START);
+ distributedCache.lifecycleEvent(LifecycleTypeAdapter.START);
}
}
@@ -363,18 +413,21 @@ public class GemfireSessionManager implements SessionManager {
*/
private void initializeSessionCache(FilterConfig config) {
// Retrieve the distributedCache
- InternalCache cache = (InternalCache) CacheFactory.getAnyInstance();
+ GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getAnyInstance();
if (cache == null) {
throw new IllegalStateException(
- "No cache exists. Please configure either a PeerToPeerCacheLifecycleListener or ClientServerCacheLifecycleListener in the server.xml file.");
+ "No cache exists. Please configure " + "either a PeerToPeerCacheLifecycleListener or "
+ + "ClientServerCacheLifecycleListener in the " + "server.xml file.");
}
- // Process all the init params and see if any apply to the distributedCache
+ /**
+ * Process all the init params and see if any apply to the distributedCache
+ */
ResourceManager rm = cache.getResourceManager();
for (Enumeration<String> e = config.getInitParameterNames(); e.hasMoreElements();) {
String param = e.nextElement();
- // Ugh - don't like this non-generic stuff
+ // Uggh - don't like this non-generic stuff
if (param.equalsIgnoreCase("criticalHeapPercentage")) {
float val = Float.parseFloat(config.getInitParameter(param));
rm.setCriticalHeapPercentage(val);
@@ -391,41 +444,37 @@ public class GemfireSessionManager implements SessionManager {
}
String gemfireWebParam = param.substring(GEMFIRE_CACHE.length());
- this.logger.info("Setting cache parameter: {} = {}", gemfireWebParam,
- config.getInitParameter(param));
- this.properties.put(CacheProperty.valueOf(gemfireWebParam.toUpperCase()),
+ LOG.info("Setting cache parameter: {} = {}", gemfireWebParam, config.getInitParameter(param));
+ properties.put(CacheProperty.valueOf(gemfireWebParam.toUpperCase()),
config.getInitParameter(param));
}
// Create the appropriate session distributedCache
- if (cache.isClient()) {
- this.sessionCache = new ClientServerSessionCache((ClientCache) cache, this.properties);
- } else {
- this.sessionCache = new PeerToPeerSessionCache(cache, this.properties);
- }
+ sessionCache = cache.isClient() ? new ClientServerSessionCache(cache, properties)
+ : new PeerToPeerSessionCache(cache, properties);
// Initialize the session distributedCache
- this.sessionCache.initialize();
+ sessionCache.initialize();
}
/**
* Register a bean for statistic gathering purposes
*/
- private void registerMBean(final SessionStatistics mBean) throws NamingException {
- InitialContext ctx = new InitialContext();
+ private void registerMBean() {
+ mbean = new SessionStatistics();
+
try {
- MBeanServer mBeanServer = MBeanServer.class.cast(ctx.lookup("java:comp/env/jmx/runtime"));
- ObjectName objectName = new ObjectName(Constants.SESSION_STATISTICS_MBEAN_NAME);
-
- mBeanServer.registerMBean(mBean, objectName);
- } catch (MalformedObjectNameException | NotCompliantMBeanException
- | InstanceAlreadyExistsException | MBeanRegistrationException e) {
- this.logger.warn("Unable to register statistics MBean. Error: {}", e.getMessage(), e);
- } finally {
- ctx.close();
+ InitialContext ctx = new InitialContext();
+ MBeanServer mbs = MBeanServer.class.cast(ctx.lookup("java:comp/env/jmx/runtime"));
+ ObjectName oname = new ObjectName(Constants.SESSION_STATISTICS_MBEAN_NAME);
+
+ mbs.registerMBean(mbean, oname);
+ } catch (Exception ex) {
+ LOG.warn("Unable to register statistics MBean. Error: {}", ex.getMessage());
}
}
+
/**
* Generate an ID string
*/
@@ -434,23 +483,6 @@ public class GemfireSessionManager implements SessionManager {
}
AbstractCache getCache() {
- return this.distributedCache;
- }
-
- private EnumMap<CacheProperty, Object> createPropertiesEnumMap() {
- EnumMap<CacheProperty, Object> cacheProperties = new EnumMap<>(CacheProperty.class);
- cacheProperties.put(CacheProperty.REGION_NAME, RegionHelper.NAME + "_sessions");
- cacheProperties.put(CacheProperty.ENABLE_GATEWAY_DELTA_REPLICATION, Boolean.FALSE);
- cacheProperties.put(CacheProperty.ENABLE_GATEWAY_REPLICATION, Boolean.FALSE);
- cacheProperties.put(CacheProperty.ENABLE_DEBUG_LISTENER, Boolean.FALSE);
- cacheProperties.put(CacheProperty.STATISTICS_NAME, "gemfire_statistics");
- cacheProperties.put(CacheProperty.SESSION_DELTA_POLICY, "delta_queued");
- cacheProperties.put(CacheProperty.REPLICATION_TRIGGER, "set");
- /*
- * For REGION_ATTRIBUTES_ID and ENABLE_LOCAL_CACHE the default is different for
- * ClientServerCache and PeerToPeerCache so those values are set in the relevant constructors
- * when these properties are passed in to them.
- */
- return cacheProperties;
+ return distributedCache;
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/8437e65b/extensions/geode-modules/src/main/java/org/apache/geode/modules/session/catalina/DeltaSessionManager.java
----------------------------------------------------------------------
diff --git a/extensions/geode-modules/src/main/java/org/apache/geode/modules/session/catalina/DeltaSessionManager.java b/extensions/geode-modules/src/main/java/org/apache/geode/modules/session/catalina/DeltaSessionManager.java
index 16274c5..edc2b7d 100644
--- a/extensions/geode-modules/src/main/java/org/apache/geode/modules/session/catalina/DeltaSessionManager.java
+++ b/extensions/geode-modules/src/main/java/org/apache/geode/modules/session/catalina/DeltaSessionManager.java
@@ -14,13 +14,33 @@
*/
package org.apache.geode.modules.session.catalina;
-import static org.apache.geode.internal.util.IOUtils.close;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.query.Query;
+import org.apache.geode.cache.query.QueryService;
+import org.apache.geode.cache.query.SelectResults;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.modules.session.catalina.internal.DeltaSessionStatistics;
+import org.apache.geode.modules.util.ContextMapper;
+import org.apache.geode.modules.util.RegionConfiguration;
+import org.apache.geode.modules.util.RegionHelper;
+import org.apache.catalina.Container;
+import org.apache.catalina.Context;
+import org.apache.catalina.Lifecycle;
+import org.apache.catalina.Loader;
+import org.apache.catalina.Pipeline;
+import org.apache.catalina.Session;
+import org.apache.catalina.Valve;
+import org.apache.catalina.session.ManagerBase;
+import org.apache.catalina.session.StandardSession;
+import org.apache.catalina.util.CustomObjectInputStream;
+import org.apache.juli.logging.Log;
+import org.apache.juli.logging.LogFactory;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
-import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -38,41 +58,10 @@ import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.servlet.http.HttpSession;
-
-import org.apache.catalina.Container;
-import org.apache.catalina.Context;
-import org.apache.catalina.Lifecycle;
-import org.apache.catalina.Loader;
-import org.apache.catalina.Pipeline;
-import org.apache.catalina.Session;
-import org.apache.catalina.Valve;
-import org.apache.catalina.session.ManagerBase;
-import org.apache.catalina.session.StandardSession;
-import org.apache.catalina.util.CustomObjectInputStream;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.client.ClientCache;
-import org.apache.geode.cache.query.Query;
-import org.apache.geode.cache.query.QueryService;
-import org.apache.geode.cache.query.SelectResults;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.modules.session.catalina.internal.DeltaSessionStatistics;
-import org.apache.geode.modules.util.ContextMapper;
-import org.apache.geode.modules.util.RegionConfiguration;
-import org.apache.geode.modules.util.RegionHelper;
-public abstract class DeltaSessionManager extends ManagerBase
+abstract public class DeltaSessionManager extends ManagerBase
implements Lifecycle, PropertyChangeListener, SessionManager {
- private static final Pattern PATTERN_SLASH = Pattern.compile("/", Pattern.LITERAL);
-
/**
* The number of rejected sessions.
*/
@@ -84,12 +73,12 @@ public abstract class DeltaSessionManager extends ManagerBase
protected int maxActiveSessions = -1;
/**
- * Has this {@code Manager} been started?
+ * Has this <code>Manager</code> been started?
*/
protected AtomicBoolean started = new AtomicBoolean(false);
/**
- * The name of this {@code Manager}
+ * The name of this <code>Manager</code>
*/
protected String name;
@@ -117,7 +106,7 @@ public abstract class DeltaSessionManager extends ManagerBase
* This *MUST* only be assigned during start/startInternal otherwise it will be associated with
* the incorrect context class loader.
*/
- protected Log logger;
+ protected Log LOGGER;
protected String regionName = DEFAULT_REGION_NAME;
@@ -148,7 +137,7 @@ public abstract class DeltaSessionManager extends ManagerBase
private static final long TIMER_TASK_DELAY =
Long.getLong("gemfiremodules.sessionTimerTaskDelay", 10000);
- protected DeltaSessionManager() {
+ public DeltaSessionManager() {
// Create the set to store sessions to be touched after get attribute requests
this.sessionsToTouch = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
}
@@ -204,7 +193,7 @@ public abstract class DeltaSessionManager extends ManagerBase
public void setMaxActiveSessions(int maxActiveSessions) {
int oldMaxActiveSessions = this.maxActiveSessions;
this.maxActiveSessions = maxActiveSessions;
- this.support.firePropertyChange("maxActiveSessions", new Integer(oldMaxActiveSessions),
+ support.firePropertyChange("maxActiveSessions", new Integer(oldMaxActiveSessions),
new Integer(this.maxActiveSessions));
}
@@ -256,7 +245,7 @@ public abstract class DeltaSessionManager extends ManagerBase
@Override
public boolean isBackingCacheAvailable() {
- return this.sessionCache.isBackingCacheAvailable();
+ return sessionCache.isBackingCacheAvailable();
}
public void setPreferDeserializedForm(boolean enable) {
@@ -270,15 +259,15 @@ public abstract class DeltaSessionManager extends ManagerBase
@Override
public String getStatisticsName() {
- return PATTERN_SLASH.matcher(getContextName()).replaceAll(Matcher.quoteReplacement(""));
+ return getContextName().replace("/", "");
}
@Override
public Log getLogger() {
- if (this.logger == null) {
- this.logger = LogFactory.getLog(DeltaSessionManager.class);
+ if (LOGGER == null) {
+ LOGGER = LogFactory.getLog(DeltaSessionManager.class);
}
- return this.logger;
+ return LOGGER;
}
public SessionCache getSessionCache() {
@@ -309,18 +298,18 @@ public abstract class DeltaSessionManager extends ManagerBase
@Override
public void setContainer(Container container) {
// De-register from the old Container (if any)
- if (Context.class.isInstance(this.container)) {
- this.container.removePropertyChangeListener(this);
+ if ((this.container != null) && (this.container instanceof Context)) {
+ ((Context) this.container).removePropertyChangeListener(this);
}
// Default processing provided by our superclass
super.setContainer(container);
// Register with the new Container (if any)
- if (Context.class.isInstance(this.container)) {
+ if ((this.container != null) && (this.container instanceof Context)) {
// Overwrite the max inactive interval with the context's session timeout.
setMaxInactiveInterval(((Context) this.container).getSessionTimeout() * 60);
- this.container.addPropertyChangeListener(this);
+ ((Context) this.container).addPropertyChangeListener(this);
}
}
@@ -374,18 +363,15 @@ public abstract class DeltaSessionManager extends ManagerBase
protected void initializeSessionCache() {
// Retrieve the cache
- InternalCache cache = (InternalCache) CacheFactory.getAnyInstance();
+ GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getAnyInstance();
if (cache == null) {
throw new IllegalStateException(
"No cache exists. Please configure either a PeerToPeerCacheLifecycleListener or ClientServerCacheLifecycleListener in the server.xml file.");
}
// Create the appropriate session cache
- if (cache.isClient()) {
- this.sessionCache = new ClientServerSessionCache(this, (ClientCache) cache);
- } else {
- this.sessionCache = new PeerToPeerSessionCache(this, cache);
- }
+ this.sessionCache = cache.isClient() ? new ClientServerSessionCache(this, cache)
+ : new PeerToPeerSessionCache(this, cache);
// Initialize the session cache
this.sessionCache.initialize();
@@ -444,7 +430,6 @@ public abstract class DeltaSessionManager extends ManagerBase
return this.rejectedSessions.get();
}
- @Override
public void setRejectedSessions(int rejectedSessions) {
this.rejectedSessions.set(rejectedSessions);
}
@@ -473,7 +458,7 @@ public abstract class DeltaSessionManager extends ManagerBase
while (sessionIds.hasNext()) {
builder.append(sessionIds.next());
if (sessionIds.hasNext()) {
- builder.append(' ');
+ builder.append(" ");
}
}
return builder.toString();
@@ -519,11 +504,12 @@ public abstract class DeltaSessionManager extends ManagerBase
@Override
public void run() {
// Get the sessionIds to touch and clear the set inside synchronization
- Set<String> sessionIds = new HashSet<>(getSessionsToTouch());
+ Set<String> sessionIds = null;
+ sessionIds = new HashSet<String>(getSessionsToTouch());
getSessionsToTouch().clear();
// Touch the sessions we currently have
- if (!sessionIds.isEmpty()) {
+ if (sessionIds != null && (!sessionIds.isEmpty())) {
getSessionCache().touchSessions(sessionIds);
if (getLogger().isDebugEnabled()) {
getLogger().debug(DeltaSessionManager.this + ": Touched sessions: " + sessionIds);
@@ -535,7 +521,7 @@ public abstract class DeltaSessionManager extends ManagerBase
}
protected void cancelTimer() {
- if (this.timer != null) {
+ if (timer != null) {
this.timer.cancel();
}
}
@@ -573,8 +559,8 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getLogger().isDebugEnabled()) {
getLogger().debug(this + ": Registering JVM route binder valve");
}
- this.jvmRouteBinderValve = new JvmRouteBinderValve();
- getPipeline().addValve(this.jvmRouteBinderValve);
+ jvmRouteBinderValve = new JvmRouteBinderValve();
+ getPipeline().addValve(jvmRouteBinderValve);
}
protected Pipeline getPipeline() {
@@ -585,8 +571,8 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getLogger().isDebugEnabled()) {
getLogger().debug(this + ": Unregistering JVM route binder valve");
}
- if (this.jvmRouteBinderValve != null) {
- getPipeline().removeValve(this.jvmRouteBinderValve);
+ if (jvmRouteBinderValve != null) {
+ getPipeline().removeValve(jvmRouteBinderValve);
}
}
@@ -594,19 +580,21 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getLogger().isDebugEnabled()) {
getLogger().debug(this + ": Registering CommitSessionValve");
}
- this.commitSessionValve = new CommitSessionValve();
- getPipeline().addValve(this.commitSessionValve);
+ commitSessionValve = new CommitSessionValve();
+ getPipeline().addValve(commitSessionValve);
}
protected void unregisterCommitSessionValve() {
if (getLogger().isDebugEnabled()) {
getLogger().debug(this + ": Unregistering CommitSessionValve");
}
- if (this.commitSessionValve != null) {
- getPipeline().removeValve(this.commitSessionValve);
+ if (commitSessionValve != null) {
+ getPipeline().removeValve(commitSessionValve);
}
}
+ // ------------------------------ Lifecycle Methods
+
/**
* Process property change events from our associated Context.
* <p>
@@ -616,6 +604,7 @@ public abstract class DeltaSessionManager extends ManagerBase
* session timeout value specified in the web.xml.
* <p>
* The precedence order for setting the session timeout value is:
+ * <p>
* <ol>
* <li>the max inactive interval is set based on the Manager defined in the context.xml
* <li>the max inactive interval is then overwritten by the value of the Context's session timeout
@@ -633,16 +622,17 @@ public abstract class DeltaSessionManager extends ManagerBase
if (!(event.getSource() instanceof Context)) {
return;
}
+ Context context = (Context) event.getSource();
// Process a relevant property change
if (event.getPropertyName().equals("sessionTimeout")) {
try {
- int interval = (Integer) event.getNewValue();
+ int interval = ((Integer) event.getNewValue()).intValue();
if (interval < RegionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL) {
getLogger().warn("The configured session timeout of " + interval
+ " minutes is invalid. Using the original value of " + event.getOldValue()
+ " minutes.");
- interval = (Integer) event.getOldValue();
+ interval = ((Integer) event.getOldValue()).intValue();;
}
// StandardContext.setSessionTimeout passes -1 if the configured timeout
// is 0; otherwise it passes the value set in web.xml. If the interval
@@ -650,7 +640,7 @@ public abstract class DeltaSessionManager extends ManagerBase
// default (no expiration); otherwise set it in seconds.
setMaxInactiveInterval(interval == RegionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL
? RegionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL : interval * 60);
- } catch (NumberFormatException ignore) {
+ } catch (NumberFormatException e) {
getLogger()
.error(sm.getString("standardManager.sessionTimeout", event.getNewValue().toString()));
}
@@ -664,7 +654,7 @@ public abstract class DeltaSessionManager extends ManagerBase
* @throws IOException if an input/output error occurs
*/
protected void doUnload() throws IOException {
- QueryService querySvc = this.sessionCache.getCache().getQueryService();
+ QueryService querySvc = sessionCache.getCache().getQueryService();
Context context = getTheContext();
if (context == null) {
return;
@@ -673,10 +663,10 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getRegionName().startsWith("/")) {
regionName = getRegionName();
} else {
- regionName = '/' + getRegionName();
+ regionName = "/" + getRegionName();
}
Query query = querySvc.newQuery("select s.id from " + regionName
- + " as s where s.contextName = '" + context.getPath() + '\'');
+ + " as s where s.contextName = '" + context.getPath() + "'");
getLogger().debug("Query: " + query.getQueryString());
SelectResults results;
@@ -700,11 +690,9 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getLogger().isDebugEnabled()) {
getLogger().debug("Unloading sessions to " + store.getAbsolutePath());
}
-
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ObjectOutputStream oos = null;
-
boolean error = false;
try {
fos = new FileOutputStream(store.getAbsolutePath());
@@ -716,13 +704,31 @@ public abstract class DeltaSessionManager extends ManagerBase
throw e;
} finally {
if (error) {
- close(oos);
- close(bos);
- close(fos);
+ if (oos != null) {
+ try {
+ oos.close();
+ } catch (IOException ioe) {
+ // Ignore
+ }
+ }
+ if (bos != null) {
+ try {
+ bos.close();
+ } catch (IOException ioe) {
+ // Ignore
+ }
+ }
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (IOException ioe) {
+ // Ignore
+ }
+ }
}
}
- ArrayList<DeltaSessionInterface> list = new ArrayList<>();
+ ArrayList<DeltaSessionInterface> list = new ArrayList<DeltaSessionInterface>();
Iterator<String> elements = results.iterator();
while (elements.hasNext()) {
String id = elements.next();
@@ -736,7 +742,7 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getLogger().isDebugEnabled())
getLogger().debug("Unloading " + list.size() + " sessions");
try {
- oos.writeObject(list.size());
+ oos.writeObject(new Integer(list.size()));
for (DeltaSessionInterface session : list) {
if (session instanceof StandardSession) {
StandardSession standardSession = (StandardSession) session;
@@ -749,12 +755,24 @@ public abstract class DeltaSessionManager extends ManagerBase
}
} catch (IOException e) {
getLogger().error("Exception unloading sessions", e);
- close(oos);
+ try {
+ oos.close();
+ } catch (IOException f) {
+ // Ignore
+ }
throw e;
}
// Flush and close the output stream
- close(oos);
+ try {
+ oos.flush();
+ } finally {
+ try {
+ oos.close();
+ } catch (IOException f) {
+ // Ignore
+ }
+ }
// Locally destroy the sessions we just wrote
if (getSessionCache().isClientServer()) {
@@ -766,6 +784,22 @@ public abstract class DeltaSessionManager extends ManagerBase
}
}
+ // // Expire all the sessions we just wrote
+ // if (getLogger().isDebugEnabled()) {
+ // getLogger().debug("Expiring " + list.size() + " persisted sessions");
+ // }
+ // Iterator<StandardSession> expires = list.iterator();
+ // while (expires.hasNext()) {
+ // StandardSession session = expires.next();
+ // try {
+ // session.expire(false);
+ // } catch (Throwable t) {
+ //// ExceptionUtils.handleThrowable(t);
+ // } finally {
+ // session.recycle();
+ // }
+ // }
+
if (getLogger().isDebugEnabled()) {
getLogger().debug("Unloading complete");
}
@@ -793,18 +827,17 @@ public abstract class DeltaSessionManager extends ManagerBase
if (getLogger().isDebugEnabled()) {
getLogger().debug("Loading sessions from " + store.getAbsolutePath());
}
-
FileInputStream fis = null;
BufferedInputStream bis = null;
- ObjectInputStream ois;
+ ObjectInputStream ois = null;
+ Loader loader = null;
+ ClassLoader classLoader = null;
try {
fis = new FileInputStream(store.getAbsolutePath());
bis = new BufferedInputStream(fis);
- Loader loader = null;
if (getTheContext() != null) {
loader = getTheContext().getLoader();
}
- ClassLoader classLoader = null;
if (loader != null) {
classLoader = loader.getClassLoader();
}
@@ -821,7 +854,7 @@ public abstract class DeltaSessionManager extends ManagerBase
}
} catch (FileNotFoundException e) {
if (getLogger().isDebugEnabled()) {
- getLogger().debug("No persisted data file found", e);
+ getLogger().debug("No persisted data file found");
}
return;
} catch (IOException e) {
@@ -829,14 +862,14 @@ public abstract class DeltaSessionManager extends ManagerBase
if (fis != null) {
try {
fis.close();
- } catch (IOException ignore) {
+ } catch (IOException f) {
// Ignore
}
}
if (bis != null) {
try {
bis.close();
- } catch (IOException ignore) {
+ } catch (IOException f) {
// Ignore
}
}
@@ -845,7 +878,8 @@ public abstract class DeltaSessionManager extends ManagerBase
// Load the previously unloaded active sessions
try {
- int n = (Integer) ois.readObject();
+ Integer count = (Integer) ois.readObject();
+ int n = count.intValue();
if (getLogger().isDebugEnabled()) {
getLogger().debug("Loading " + n + " persisted sessions");
}
@@ -854,7 +888,7 @@ public abstract class DeltaSessionManager extends ManagerBase
session.readObjectData(ois);
session.setManager(this);
- Region<String, HttpSession> region = getSessionCache().getOperatingRegion();
+ Region region = getSessionCache().getOperatingRegion();
DeltaSessionInterface existingSession = (DeltaSessionInterface) region.get(session.getId());
// Check whether the existing session is newer
if (existingSession != null
@@ -877,11 +911,19 @@ public abstract class DeltaSessionManager extends ManagerBase
session.activate();
add(session);
}
- } catch (ClassNotFoundException | IOException e) {
+ } catch (ClassNotFoundException e) {
getLogger().error(e);
try {
ois.close();
- } catch (IOException ignore) {
+ } catch (IOException f) {
+ // Ignore
+ }
+ throw e;
+ } catch (IOException e) {
+ getLogger().error(e);
+ try {
+ ois.close();
+ } catch (IOException f) {
// Ignore
}
throw e;
@@ -889,7 +931,7 @@ public abstract class DeltaSessionManager extends ManagerBase
// Close the input stream
try {
ois.close();
- } catch (IOException ignore) {
+ } catch (IOException f) {
// ignored
}
@@ -910,14 +952,16 @@ public abstract class DeltaSessionManager extends ManagerBase
} else {
storeDir += System.getProperty("file.separator") + "temp";
}
- return new File(storeDir, PATTERN_SLASH.matcher(ctxPath).replaceAll("_") + ".sessions.ser");
+ File file = new File(storeDir, ctxPath.replaceAll("/", "_") + ".sessions.ser");
+
+ return (file);
}
@Override
public String toString() {
- return new StringBuilder().append(getClass().getSimpleName()).append('[').append("container=")
+ return new StringBuilder().append(getClass().getSimpleName()).append("[").append("container=")
.append(getTheContext()).append("; regionName=").append(this.regionName)
- .append("; regionAttributesId=").append(this.regionAttributesId).append(']').toString();
+ .append("; regionAttributesId=").append(this.regionAttributesId).append("]").toString();
}
protected String getContextName() {
http://git-wip-us.apache.org/repos/asf/geode/blob/8437e65b/extensions/geode-modules/src/main/java/org/apache/geode/modules/util/CreateRegionFunction.java
----------------------------------------------------------------------
diff --git a/extensions/geode-modules/src/main/java/org/apache/geode/modules/util/CreateRegionFunction.java b/extensions/geode-modules/src/main/java/org/apache/geode/modules/util/CreateRegionFunction.java
index d10ff2a..4e9e9fd 100644
--- a/extensions/geode-modules/src/main/java/org/apache/geode/modules/util/CreateRegionFunction.java
+++ b/extensions/geode-modules/src/main/java/org/apache/geode/modules/util/CreateRegionFunction.java
@@ -24,18 +24,19 @@ import org.apache.geode.InternalGemFireError;
import org.apache.geode.cache.AttributesFactory;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.CacheWriterException;
import org.apache.geode.cache.Declarable;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.Scope;
-import org.apache.geode.cache.TimeoutException;
+import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.partition.PartitionRegionHelper;
import org.apache.geode.distributed.DistributedLockService;
import org.apache.geode.distributed.internal.locks.DistributedMemberLock;
-import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.cache.InternalRegionArguments;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
@@ -57,16 +58,20 @@ public class CreateRegionFunction implements Function, Declarable {
private static final String REGION_CONFIGURATION_METADATA_REGION =
"__regionConfigurationMetadata";
- CreateRegionFunction() {
+ public CreateRegionFunction() {
this(CacheFactory.getAnyInstance());
}
- private CreateRegionFunction(Cache cache) {
+ public CreateRegionFunction(Cache cache) {
this.cache = cache;
this.regionConfigurationsRegion = createRegionConfigurationMetadataRegion();
}
- @Override
+ public CreateRegionFunction(ClientCache cache) {
+ this.cache = null;
+ this.regionConfigurationsRegion = null;
+ }
+
public void execute(FunctionContext context) {
RegionConfiguration configuration = (RegionConfiguration) context.getArguments();
if (this.cache.getLogger().fineEnabled()) {
@@ -87,19 +92,19 @@ public class CreateRegionFunction implements Function, Declarable {
}
private RegionStatus createOrRetrieveRegion(RegionConfiguration configuration) {
+ RegionStatus status = null;
String regionName = configuration.getRegionName();
if (this.cache.getLogger().fineEnabled()) {
this.cache.getLogger().fine("Function " + ID + " retrieving region named: " + regionName);
}
- Region<Object, Object> region = this.cache.getRegion(regionName);
- RegionStatus status;
+ Region region = this.cache.getRegion(regionName);
if (region == null) {
status = createRegion(configuration);
} else {
status = RegionStatus.VALID;
try {
RegionHelper.validateRegion(this.cache, configuration, region);
- } catch (RuntimeException e) {
+ } catch (Exception e) {
if (!e.getMessage()
.equals(LocalizedStrings.RegionAttributesCreation_CACHELISTENERS_ARE_NOT_THE_SAME
.toLocalizedString())) {
@@ -111,28 +116,23 @@ public class CreateRegionFunction implements Function, Declarable {
return status;
}
- @Override
public String getId() {
return ID;
}
- @Override
public boolean optimizeForWrite() {
return false;
}
- @Override
public boolean isHA() {
return true;
}
- @Override
public boolean hasResult() {
return true;
}
- @Override
- public void init(Properties props) {}
+ public void init(Properties properties) {}
private RegionStatus createRegion(RegionConfiguration configuration) {
// Get a distributed lock
@@ -140,23 +140,23 @@ public class CreateRegionFunction implements Function, Declarable {
if (this.cache.getLogger().fineEnabled()) {
this.cache.getLogger().fine(this + ": Attempting to lock " + dml);
}
- RegionStatus status;
+ long start = 0, end = 0;
+ RegionStatus status = null;
try {
- long start = 0;
if (this.cache.getLogger().fineEnabled()) {
start = System.currentTimeMillis();
}
// Obtain a lock on the distributed lock
dml.lockInterruptibly();
if (this.cache.getLogger().fineEnabled()) {
- long end = System.currentTimeMillis();
+ end = System.currentTimeMillis();
this.cache.getLogger()
.fine(this + ": Obtained lock on " + dml + " in " + (end - start) + " ms");
}
// Attempt to get the region again after the lock has been obtained
String regionName = configuration.getRegionName();
- Region<Object, Object> region = this.cache.getRegion(regionName);
+ Region region = this.cache.getRegion(regionName);
// If it exists now, validate it.
// Else put an entry into the sessionRegionConfigurationsRegion
@@ -182,7 +182,7 @@ public class CreateRegionFunction implements Function, Declarable {
status = RegionStatus.VALID;
try {
RegionHelper.validateRegion(this.cache, configuration, region);
- } catch (RuntimeException e) {
+ } catch (Exception e) {
if (!e.getMessage()
.equals(LocalizedStrings.RegionAttributesCreation_CACHELISTENERS_ARE_NOT_THE_SAME
.toLocalizedString())) {
@@ -191,17 +191,17 @@ public class CreateRegionFunction implements Function, Declarable {
status = RegionStatus.INVALID;
}
}
- } catch (InterruptedException | CacheWriterException | TimeoutException e) {
+ } catch (Exception e) {
StringBuilder builder = new StringBuilder();
builder.append(this).append(": Caught Exception attempting to create region named ")
- .append(configuration.getRegionName()).append(':');
+ .append(configuration.getRegionName()).append(":");
this.cache.getLogger().warning(builder.toString(), e);
status = RegionStatus.INVALID;
} finally {
// Unlock the distributed lock
try {
dml.unlock();
- } catch (RuntimeException ignore) {
+ } catch (Exception ignore) {
}
}
return status;
@@ -219,17 +219,19 @@ public class CreateRegionFunction implements Function, Declarable {
if (r != null) {
return r;
}
- InternalCache internalCache = (InternalCache) this.cache;
+ GemFireCacheImpl gemFireCache = (GemFireCacheImpl) cache;
InternalRegionArguments ira = new InternalRegionArguments().setInternalRegion(true);
- AttributesFactory<String, RegionConfiguration> af = new AttributesFactory<>();
+ AttributesFactory af = new AttributesFactory();
af.setScope(Scope.LOCAL);
af.addCacheListener(new RegionConfigurationCacheListener());
- RegionAttributes<String, RegionConfiguration> ra = af.create();
+ RegionAttributes ra = af.create();
try {
- return internalCache.createVMRegion(REGION_CONFIGURATION_METADATA_REGION, ra, ira);
+ return gemFireCache.createVMRegion(REGION_CONFIGURATION_METADATA_REGION, ra, ira);
} catch (IOException | ClassNotFoundException e) {
- throw new InternalGemFireError(
- LocalizedStrings.GemFireCache_UNEXPECTED_EXCEPTION.toLocalizedString(), e);
+ InternalGemFireError assErr = new InternalGemFireError(
+ LocalizedStrings.GemFireCache_UNEXPECTED_EXCEPTION.toLocalizedString());
+ assErr.initCause(e);
+ throw assErr;
}
}
@@ -239,7 +241,7 @@ public class CreateRegionFunction implements Function, Declarable {
PrintWriter pw = new PrintWriter(new FileWriter(file), true);
CacheXmlGenerator.generate(this.cache, pw);
pw.close();
- } catch (IOException ignore) {
+ } catch (IOException e) {
}
}