JBoss Cache SVN: r6548 - core/trunk/src/main/java/org/jboss/cache/util.
by jbosscache-commits@lists.jboss.org
Author: jason.greene(a)jboss.com
Date: 2008-08-08 14:43:15 -0400 (Fri, 08 Aug 2008)
New Revision: 6548
Modified:
core/trunk/src/main/java/org/jboss/cache/util/Immutables.java
Log:
Fix type-o
Add fast-path for known collection types
Modified: core/trunk/src/main/java/org/jboss/cache/util/Immutables.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/util/Immutables.java 2008-08-08 17:05:16 UTC (rev 6547)
+++ core/trunk/src/main/java/org/jboss/cache/util/Immutables.java 2008-08-08 18:43:15 UTC (rev 6548)
@@ -28,9 +28,13 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
import java.util.Map.Entry;
/**
@@ -127,11 +131,12 @@
*/
public static <T> Set<T> immutableSetCopy(Set<? extends T> set)
{
- Set<? extends T> copy = attemptClone(set);
+ Set<? extends T> copy = attemptKnownSetCopy(set);
if (copy == null)
+ attemptClone(set);
+ if (copy == null)
// Set uses Collection copy-ctor
copy = attemptCopyConstructor(set, Collection.class);
-
if (copy == null)
copy = new HashSet<T>(set);
@@ -158,13 +163,16 @@
*/
public static <K,V> Map<K,V> immutableMapCopy(Map<? extends K, ? extends V> map)
{
- Map<? extends K, ? extends V> copy = attemptClone(map);
+ Map<? extends K, ? extends V> copy = attemptKnownMapCopy(map);
+
if (copy == null)
+ attemptClone(map);
+ if (copy == null)
copy = attemptCopyConstructor(map, Map.class);
if (copy == null)
copy = new HashMap<K,V>(map);
- return new ImmutableMapWrapper<K,V>(map);
+ return new ImmutableMapWrapper<K,V>(copy);
}
/**
@@ -175,17 +183,46 @@
*/
public static <T> Collection<T> immutableCollectionCopy(Collection<? extends T> collection)
{
- Collection<? extends T> copy = attemptClone(collection);
+ Collection<? extends T> copy = attemptKnownSetCopy(collection);
if (copy == null)
+ copy = attemptClone(collection);
+ if (copy == null)
copy = attemptCopyConstructor(collection, Collection.class);
if (copy == null)
copy = new ArrayList<T>(collection);
- return new ImmutableCollectionWrapper<T>(collection);
+ return new ImmutableCollectionWrapper<T>(copy);
}
+ @SuppressWarnings("unchecked")
+ private static <T extends Map> T attemptKnownMapCopy(T map)
+ {
+ if (map instanceof FastCopyHashMap)
+ return (T)((FastCopyHashMap) map).clone();
+ if (map instanceof HashMap)
+ return (T)((HashMap) map).clone();
+ if (map instanceof LinkedHashMap)
+ return (T)((LinkedHashMap) map).clone();
+ if (map instanceof TreeMap)
+ return (T)((TreeMap) map).clone();
+ return null;
+ }
+
@SuppressWarnings("unchecked")
+ private static <T extends Collection> T attemptKnownSetCopy(T set)
+ {
+ if (set instanceof HashSet)
+ return (T)((HashSet) set).clone();
+ if (set instanceof LinkedHashSet)
+ return (T)((LinkedHashSet) set).clone();
+ if (set instanceof TreeSet)
+ return (T)((TreeSet) set).clone();
+
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
private static <T> T attemptClone(T source)
{
if (source instanceof Cloneable)
@@ -537,5 +574,10 @@
{
return new ImmutableCollectionWrapper<V>(map.values());
}
+
+ public String toString()
+ {
+ return map.toString();
+ }
}
}
16 years, 5 months
JBoss Cache SVN: r6547 - core/trunk/src/main/java/org/jboss/cache/config.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-08-08 13:05:16 -0400 (Fri, 08 Aug 2008)
New Revision: 6547
Modified:
core/trunk/src/main/java/org/jboss/cache/config/Configuration.java
Log:
Deprecation
Modified: core/trunk/src/main/java/org/jboss/cache/config/Configuration.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/Configuration.java 2008-08-08 17:00:29 UTC (rev 6546)
+++ core/trunk/src/main/java/org/jboss/cache/config/Configuration.java 2008-08-08 17:05:16 UTC (rev 6547)
@@ -661,11 +661,20 @@
return replQueueInterval;
}
+ /**
+ * @deprecated use isExposeManagementStatistics()
+ */
+ @Deprecated
public boolean getExposeManagementStatistics()
{
return exposeManagementStatistics;
}
+ public boolean isExposeManagementStatistics()
+ {
+ return exposeManagementStatistics;
+ }
+
/**
* @return true if invocation batching is enabled.
* @since 3.0
16 years, 5 months
JBoss Cache SVN: r6546 - in core/trunk/src: test/java/org/jboss/cache/jmx and 1 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-08-08 13:00:29 -0400 (Fri, 08 Aug 2008)
New Revision: 6546
Added:
core/trunk/src/main/java/org/jboss/cache/jmx/JmxRegistrationManager.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTestBase.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/NotificationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java
Removed:
core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java
core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/LegacyConfigurationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/LifecycleNotificationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/NotificationTest.java
core/trunk/src/test/java/org/jboss/cache/jmx/OptimisticNotificationTest.java
Modified:
core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java
core/trunk/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java
Log:
ongoing JMX stuff - deprecated old CacheJmxWrapper
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -24,13 +24,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.*;
-import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.config.*;
import org.jboss.cache.config.parsing.JGroupsStackParser;
import org.jboss.cache.config.parsing.element.BuddyElementParser;
import org.jboss.cache.config.parsing.element.EvictionElementParser;
import org.jboss.cache.config.parsing.element.LoadersElementParser;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.util.CachePrinter;
import org.jgroups.Address;
import org.jgroups.Channel;
@@ -40,18 +38,19 @@
import javax.management.*;
import javax.transaction.TransactionManager;
-import java.util.List;
import java.util.ArrayList;
+import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
- * Wrapper class that exposes a
- * {@link CacheJmxWrapperMBean JMX management interface}
+ * Wrapper class that exposes a {@link CacheJmxWrapperMBean JMX management interface}
*
* @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
* @version $Revision$
+ * @deprecated use {@link org.jboss.cache.jmx.JmxRegistrationManager}. This class will not be supported from 3.0 on.
*/
+@Deprecated
public class CacheJmxWrapper<K, V>
extends NotificationBroadcasterSupport
implements CacheJmxWrapperMBean<K, V>, MBeanRegistration, CacheNotificationBroadcaster
@@ -708,27 +707,20 @@
throws Exception
{
this.server = server;
-
if (cacheObjectName == null)
{
- if (objName == null)
+ if (objName != null)
{
- // Calling this will create a value for cacheObjectName
+ cacheObjectName = objName.getCanonicalName();
+ } else
+ {
getCacheObjectName();
}
- else
- {
- cacheObjectName = objName.getCanonicalName();
- }
}
-
- ObjectName result = new ObjectName(cacheObjectName);
-
// Inform our CacheNotificationListener of the ObjectName it should transmit
- if (notificationServiceName == null)
- notificationServiceName = result.getCanonicalName();
+ if (notificationServiceName == null) notificationServiceName = cacheObjectName;
cacheNotificationListener.setServiceName(notificationServiceName);
- return result;
+ return new ObjectName(cacheObjectName);
}
/**
@@ -817,7 +809,14 @@
{
if (cacheObjectName == null)
{
- cacheObjectName = JmxUtil.getDefaultCacheObjectName(config, CacheSPI.class.getName());
+ if (config.getClusterName() == null)
+ {
+ cacheObjectName = JmxRegistrationManager.LOCAL_CACHE_PREFIX + "Cache" + System.currentTimeMillis();
+ }
+ else
+ {
+ cacheObjectName = JmxRegistrationManager.CLUSTERED_CACHE_PREFIX + config.getClusterName();
+ }
}
return cacheObjectName;
}
@@ -939,33 +938,10 @@
if (registerJmxResource && config.getExposeManagementStatistics() && !jmxResourceRegistered && server != null)
{
log.debug("Registering jmx resources");
- List<CommandInterceptor> interc = cache.getInterceptorChain();
- if (interc != null && interc.size() > 0)
- {
- try
- {
- for (ComponentRegistry.Component component : cache.getComponentRegistry().getRegiteredComponents())
- {
- ResourceDMBean resourceDMBean = new ResourceDMBean(component.getInstance());
- if (resourceDMBean.isManagedResource())
- {
- resourceDMBeans.add(resourceDMBean);
- }
- }
- for (ResourceDMBean resource: resourceDMBeans)
- {
- String resourceName = resource.getObject().getClass().getSimpleName();
- ObjectName objectName = new ObjectName(cacheObjectName + JmxUtil.JMX_RESOURCE_KEY + resourceName);
- if (!server.isRegistered(objectName)) server.registerMBean(resource, objectName);
- }
- jmxResourceRegistered = true;
- return true;
- }
- catch (JMException e)
- {
- throw new CacheException("Failed to register jmx resources", e);
- }
- }
+ JmxRegistrationManager registrationManager = new JmxRegistrationManager(server, cache, this.cacheObjectName);
+ registrationManager.registerAllMBeans();
+ jmxResourceRegistered = true;
+ return true;
}
return false;
}
@@ -974,21 +950,10 @@
{
if (registerJmxResource && jmxResourceRegistered && server != null)
{
- try
- {
- log.debug("Unregistering interceptors");
- for (ResourceDMBean resource : resourceDMBeans)
- {
- String resourceName = resource.getObject().getClass().getSimpleName();
- ObjectName objectName = new ObjectName(cacheObjectName + JmxUtil.JMX_RESOURCE_KEY + resourceName);
- if (server.isRegistered(objectName)) server.unregisterMBean(objectName);
- }
- jmxResourceRegistered = false;
- }
- catch (Exception e)
- {
- log.error("Exception unregistering interceptors from JMX", e);
- }
+ log.debug("Unregistering interceptors");
+ JmxRegistrationManager registrationManager = new JmxRegistrationManager(server, cache, this.cacheObjectName);
+ registrationManager.unregisterAllMBeans();
+ jmxResourceRegistered = false;
}
}
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -25,7 +25,9 @@
* <li> Cache information methods (numNodes, numAttributes, lockInfo, printDetails) which print as Strings or as formatted HTML (for web based JMX consoles)</li>
*
* @since 2.0.0
+ * @deprecated use {@link org.jboss.cache.jmx.JmxRegistrationManager}
*/
+@Deprecated
public interface CacheJmxWrapperMBean<K, V> extends LegacyConfiguration
{
/**
Added: core/trunk/src/main/java/org/jboss/cache/jmx/JmxRegistrationManager.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/JmxRegistrationManager.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/JmxRegistrationManager.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,191 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx;
+
+import org.jboss.cache.Cache;
+import org.jboss.cache.CacheSPI;
+import org.jboss.cache.CacheException;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.factories.ComponentRegistry;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.management.*;
+import java.lang.management.ManagementFactory;
+import java.util.List;
+import java.util.ArrayList;
+
+/**
+ * @author Mircea.Markus(a)jboss.com
+ * @since 3.0
+ */
+public class JmxRegistrationManager
+{
+
+ private static final Log log = LogFactory.getLog(JmxRegistrationManager.class);
+
+ /**
+ * default ObjectName for clusterd caches. Cluster name should pe appended.
+ */
+ public static final String CLUSTERED_CACHE_PREFIX = "jboss.cache:service=JBossCache,cluster=";
+
+ /**
+ * default ObjectName for non clustered caches. An unique identifier should be appended.
+ */
+ public static final String LOCAL_CACHE_PREFIX = "jboss.cache:service=JBossCache,uniqueId=";
+
+ /**
+ * Key for every Dynamic mbean added.
+ */
+ public static final String JMX_RESOURCE_KEY = ",jmx-resource=";
+
+ private MBeanServer mBeanServer;
+
+ private String objectNameBase;
+
+ private CacheSPI cacheSpi;
+
+ public JmxRegistrationManager(MBeanServer mBeanServer, Cache cache, ObjectName objectNameBase)
+ {
+ this.mBeanServer = mBeanServer;
+ this.cacheSpi = (CacheSPI) cache;
+ processBaseName(objectNameBase);
+ }
+
+ /**
+ * @param mBeanServer
+ * @param cache
+ * @param objectNameBase
+ * @throws IllegalArgumentException if the supplied objectNameBase name isn't valid
+ */
+ public JmxRegistrationManager(MBeanServer mBeanServer, Cache cache, String objectNameBase)
+ {
+ this.mBeanServer = mBeanServer;
+ this.cacheSpi = (CacheSPI) cache;
+ try
+ {
+ processBaseName(new ObjectName(objectNameBase));
+ } catch (MalformedObjectNameException e)
+ {
+ throw new IllegalArgumentException("Invalid Object Name : " + objectNameBase, e);
+ }
+ }
+
+ /**
+ * Defaults to platform to platform MBeanServer.
+ *
+ * @see java.lang.management.ManagementFactory#getPlatformMBeanServer()
+ * @see <a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/mxbeans.html#mbean_s...">platform MBeanServer</a>
+ */
+ public JmxRegistrationManager(Cache cache, ObjectName objectNameBase)
+ {
+ this(ManagementFactory.getPlatformMBeanServer(), cache, objectNameBase);
+ }
+
+ public JmxRegistrationManager(Cache cache)
+ {
+ this(cache, null);
+ }
+
+ public void registerAllMBeans() throws CacheException
+ {
+ try
+ {
+ List<ResourceDMBean> resourceDMBeans = getResourceDMBeans();
+ for (ResourceDMBean resource : resourceDMBeans)
+ {
+ String resourceName = resource.getObject().getClass().getSimpleName();
+ ObjectName objectName = new ObjectName(getObjectName(resourceName));
+ if (!mBeanServer.isRegistered(objectName))
+ {
+ mBeanServer.registerMBean(resource, objectName);
+ }
+ }
+ } catch (Exception e)
+ {
+ throw new CacheException("Failure while registering mbeans", e);
+ }
+ }
+
+ public void unregisterAllMBeans() throws CacheException
+ {
+ log.trace("Unregistering jmx resources..");
+ try
+ {
+ List<ResourceDMBean> resourceDMBeans = getResourceDMBeans();
+ for (ResourceDMBean resource : resourceDMBeans)
+ {
+ String resourceName = resource.getObject().getClass().getSimpleName();
+ ObjectName objectName = new ObjectName(getObjectName(resourceName));
+ if (mBeanServer.isRegistered(objectName))
+ {
+ mBeanServer.unregisterMBean(objectName);
+ }
+ }
+ } catch (Exception e)
+ {
+ throw new CacheException("Failure while unregistering mbeans", e);
+ }
+ }
+
+
+ private List<ResourceDMBean> getResourceDMBeans()
+ {
+ List<ResourceDMBean> resourceDMBeans = new ArrayList<ResourceDMBean>();
+ for (ComponentRegistry.Component component : cacheSpi.getComponentRegistry().getRegiteredComponents())
+ {
+ ResourceDMBean resourceDMBean = new ResourceDMBean(component.getInstance());
+ if (resourceDMBean.isManagedResource())
+ {
+ resourceDMBeans.add(resourceDMBean);
+ }
+ }
+ return resourceDMBeans;
+ }
+
+ private void processBaseName(ObjectName baseName)
+ {
+ if (baseName != null)
+ {
+ this.objectNameBase = baseName.getCanonicalName();
+ return;
+ }
+ if (cacheSpi.getConfiguration().getCacheMode().equals(Configuration.CacheMode.LOCAL))
+ {
+ objectNameBase = LOCAL_CACHE_PREFIX + System.currentTimeMillis();
+ }
+ else //the cache is clustered
+ {
+ objectNameBase = CLUSTERED_CACHE_PREFIX + cacheSpi.getConfiguration().getClusterName();
+ }
+ }
+
+ private String getObjectName(String resourceName)
+ {
+ return objectNameBase + JMX_RESOURCE_KEY + resourceName;
+ }
+
+ public String getObjectNameBase()
+ {
+ return objectNameBase;
+ }
+}
Deleted: core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,93 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.jmx;
-
-import org.jboss.cache.config.Configuration;
-
-import javax.management.JMException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-/**
- * Various JMX related utilities
- *
- * @author Jerry Gauthier
- * @author Manik Surtani
- * @version $Id$
- */
-public class JmxUtil
-{
- public static final String JBOSS_SERVER_DOMAIN = "jboss";
- public static final String JBOSS_CACHE_DOMAIN = "jboss.cache";
- public static final String SERVICE_KEY_NAME = "service";
- public static final String BASE_PREFIX = JBOSS_CACHE_DOMAIN + ":" + SERVICE_KEY_NAME + "=JBossCache";
- public static final String CLUSTER_KEY = "cluster";
- public static final String PREFIX = BASE_PREFIX + "," + CLUSTER_KEY + "=";
- public static final String UNIQUE_ID_KEY = "uniqueId";
- public static final String NO_CLUSTER_PREFIX = BASE_PREFIX + "," + UNIQUE_ID_KEY + "=";
- public static final String CACHE_TYPE_KEY = "cacheType";
- public static final String PLAIN_CACHE_TYPE = "Cache";
- public static final String MBEAN_CLASS_SUFFIX = "MBean";
- public static final String JMX_RESOURCE_KEY = ",jmx-resource=";
-
- public static void registerCacheMBean(MBeanServer server, CacheJmxWrapperMBean cache, String cacheObjectName)
- throws JMException
- {
- ObjectName on = new ObjectName(cacheObjectName);
- if (!server.isRegistered(on))
- {
- server.registerMBean(cache, on);
- }
- }
-
- public static String getDefaultCacheObjectName(org.jboss.cache.Cache cache)
- {
- // get the cache's registration name
- return getDefaultCacheObjectName(cache.getConfiguration(), cache.getClass().getName());
- }
-
- public static String getDefaultCacheObjectName(Configuration config, String cacheImplClass)
- {
- // get the cache's registration name
- String tmpName;
- if (config.getClusterName() == null)
- {
- tmpName = NO_CLUSTER_PREFIX + getUniqueId(cacheImplClass);
- }
- else
- {
- tmpName = PREFIX + config.getClusterName();
- }
- return tmpName;
- }
-
- public static String getUniqueId(String cacheImplClass)
- {
- return cacheImplClass + System.currentTimeMillis();
- }
-
- public static void unregisterCacheMBean(MBeanServer server, String cacheObjectName)
- throws Exception
- {
- server.unregisterMBean(new ObjectName(cacheObjectName));
- }
-}
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -33,7 +33,9 @@
*
* @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
* @version $Revision$
+ * @deprecated use {@link org.jboss.cache.jmx.JmxRegistrationManager}
*/
+@Deprecated
public interface LegacyConfiguration
{
/**
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTest.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,453 +0,0 @@
-package org.jboss.cache.jmx;
-
-import org.jboss.cache.Cache;
-import org.jboss.cache.CacheException;
-import org.jboss.cache.CacheStatus;
-import org.jboss.cache.Fqn;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.config.Configuration.CacheMode;
-import org.jboss.cache.notifications.annotation.CacheListener;
-import org.jboss.cache.notifications.annotation.CacheStarted;
-import org.jboss.cache.notifications.annotation.CacheStopped;
-import org.jboss.cache.notifications.event.Event;
-import org.jboss.cache.transaction.DummyTransactionManagerLookup;
-import org.jboss.cache.util.CachePrinter;
-import org.jboss.cache.util.TestingUtil;
-import org.jgroups.Address;
-import org.jgroups.stack.IpAddress;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.Test;
-
-import javax.management.ObjectName;
-import javax.transaction.TransactionManager;
-import java.util.List;
-
-/**
- * Tests the JMX wrapper class around the cache.
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
- * @author Brian Stansberry
- */
-@Test(groups = "functional")
-public class CacheJmxWrapperTest extends CacheJmxWrapperTestBase
-{
- public void testCacheMBeanBinding() throws Exception
- {
- registerWrapper();
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
- }
-
- public void testSetCacheObjectName() throws Exception
- {
- ObjectName on = new ObjectName("jboss.cache:test=SetCacheObjectName");
- boolean registered = false;
- try
- {
- CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- wrapper.setCacheObjectName(on.getCanonicalName());
-
- // Register under the standard name
- registerWrapper(wrapper);
- // Should be registered under 'on'
- registered = mBeanServer.isRegistered(on);
-
- assertTrue("Registered with configured name", registered);
- assertEquals("Configured name retained", on.getCanonicalName(), wrapper.getCacheObjectName());
-
- wrapper.create();
- wrapper.start();
-
- interceptorRegistrationTest(on.getCanonicalName(), true);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
- }
- finally
- {
- if (registered)
- mBeanServer.unregisterMBean(on);
- }
- }
-
- public void testGetCacheObjectName() throws Exception
- {
- ObjectName on = new ObjectName("jboss.cache:test=SetCacheObjectName");
- String str = on.getCanonicalName();
- CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- wrapper.setCacheObjectName(str);
-
- assertEquals("Setter and getter match", str, wrapper.getCacheObjectName());
-
- // Go back to the default
- wrapper.setCacheObjectName(null);
- assertEquals("Got default ObjectName", JmxUtil.PREFIX + CLUSTER_NAME, wrapper.getCacheObjectName());
-
- registerWrapper(wrapper);
- assertEquals("Returns standard name", mBeanName, new ObjectName(wrapper.getCacheObjectName()));
- }
-
- public void testGetConfiguration1() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
- Configuration cfgFromJmx = wrapper.getConfiguration();
- assertNotNull("Got a configuration", cfgFromJmx);
- assertSame(cache.getConfiguration(), cfgFromJmx);
- }
-
- public void testGetConfiguration2() throws Exception
- {
- Configuration cfg = createConfiguration();
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cfg);
- Configuration cfgFromJmx = wrapper.getConfiguration();
- assertNotNull("Got a configuration", cfgFromJmx);
- assertSame(cfg, cfgFromJmx);
- }
-
- /**
- * Note that this is a bit of a 'white box' test as it assumes that the
- * returned String equals Configuration.toString(). That could change and
- * break this test; if it does, and there's nothing wrong with the
- * change, just modify the test.
- *
- * @throws Exception
- */
- public void testPrintConfigurationAsString1() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
- String cfgFromJmx = wrapper.printConfigurationAsString();
- assertEquals(cache.getConfiguration().toString(), cfgFromJmx);
- }
-
- /**
- * Note that this is a bit of a 'white box' test as it assumes that the
- * returned String equals Configuration.toString(). That could change and
- * break this test; if it does, and there's nothing wrong with the
- * change, just modify the test.
- *
- * @throws Exception
- */
- public void testPrintConfigurationAsString2() throws Exception
- {
- Configuration cfg = createConfiguration();
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cfg);
- wrapper.create();
- wrapper.start();
- String cfgFromJmx = wrapper.printConfigurationAsString();
- assertEquals(wrapper.getCache().getConfiguration().toString(), cfgFromJmx);
- }
-
- /**
- * Note that this is a bit of a 'white box' test as it checks
- * the currently coded HTML format and assumes that the HTML content is
- * derived from Configuration.toString(). That could change and break
- * this test; if it does, and there's nothing wrong with the
- * change, just modify the test.
- *
- * @throws Exception
- */
- public void testPrintConfigurationAsHtml1() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
- String cfgFromJmx = wrapper.printConfigurationAsHtmlString();
- assertEquals(CacheJmxWrapper.formatHtml(cache.getConfiguration().toString()), cfgFromJmx);
- checkHtml(cfgFromJmx, false);
- }
-
- /**
- * Note that this is a bit of a 'white box' test as it checks
- * the currently coded HTML format and assumes that the HTML content is
- * derived from Configuration.toString(). That could change and break
- * this test; if it does, and there's nothing wrong with the
- * change, just modify the test.
- *
- * @throws Exception
- */
- public void testPrintConfigurationAsHtml2() throws Exception
- {
- Configuration cfg = createConfiguration();
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cfg);
- wrapper.create();
- wrapper.start();
- String cfgFromJmx = wrapper.printConfigurationAsHtmlString();
- assertEquals(CacheJmxWrapper.formatHtml(wrapper.getCache().getConfiguration().toString()), cfgFromJmx);
- checkHtml(cfgFromJmx, false);
- }
-
- @SuppressWarnings("unchecked")
- public void testGetCache() throws Exception
- {
- registerWrapper();
- // have to start the cache before we'll have a root
- cache.start();
-
- Cache<String, String> cacheJmx = (Cache<String, String>) mBeanServer.getAttribute(mBeanName, "Cache");
- cacheJmx.getRoot().put("key", "value");
-
- assertEquals("value", cache.getRoot().get("key"));
-
- Fqn fqn = Fqn.fromString("/testing/jmx");
- cache.put(fqn, "key", "value");
-
- assertEquals("value", cacheJmx.get(fqn, "key"));
- }
-
- public void testPrintCacheDetails() throws Exception
- {
- printCacheDetailsTest(false);
- }
-
- /**
- * Note that this is a bit of a 'white box' test as it checks
- * the currently coded HTML format. That could change and break
- * this test; if it does, and there's nothing wrong with the
- * change, just modify the test.
- *
- * @throws Exception
- */
- public void testPrintCacheDetailsAsHtml() throws Exception
- {
- String html = printCacheDetailsTest(true);
- checkHtml(html, true);
- }
-
- public void testPrintLockInfo() throws Exception
- {
- printLockInfoTest(false);
- }
-
- /**
- * Note that this is a bit of a 'white box' test as it checks
- * the currently coded HTML format. That could change and break
- * this test; if it does, and there's nothing wrong with the
- * change, just modify the test.
- *
- * @throws Exception
- */
- public void testPrintLockInfoAsHtml() throws Exception
- {
- printLockInfoTest(true);
- }
-
- public void testGetLocalAddress() throws Exception
- {
- Configuration c = createConfiguration();
- c.setCacheMode(CacheMode.REPL_ASYNC);
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(c);
- wrapper.start();
- assertTrue("Got an IpAddress", wrapper.getLocalAddress() instanceof IpAddress);
- }
-
- public void testGetMembers() throws Exception
- {
- Configuration c = createConfiguration();
- c.setCacheMode(CacheMode.REPL_ASYNC);
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(c);
- wrapper.start();
-
- c = createConfiguration();
- c.setCacheMode(CacheMode.REPL_ASYNC);
- Cache cache2 = null;
- try
- {
- cache2 = createCache(c);
- cache2.start();
- Cache[] caches = new Cache[]{wrapper.getCache(), cache2};
- TestingUtil.blockUntilViewsReceived(caches, 5000);
-
- Address addr = wrapper.getLocalAddress();
- assertNotNull("Got an Address", addr);
- List members = wrapper.getMembers();
- assertNotNull("Got members", addr);
- assertEquals("Got correct number of members", 2, members.size());
- assertTrue("I am a member", members.contains(addr));
- }
- finally
- {
- if (cache2 != null)
- {
- cache2.destroy();
- }
- }
- }
-
- public void testDuplicateInvocation() throws Exception
- {
- CacheJmxWrapperMBean<String, String> cache = registerWrapper();
- cache.create();
- cache.start();
- cache.create();
- cache.start();
-
- cache.getCache().put(Fqn.fromString("/a/b/c"), null);
- assertTrue(cache.getNumberOfNodes() > 0);
- assertEquals(0, cache.getNumberOfAttributes());
-
- System.out.println("cache locks before restart:\n" + cache.printLockInfo());
- cache.destroy();
- cache.start();
- System.out.println("cache locks after restart:\n" + cache.printLockInfo());
-
- assertEquals(0, cache.getNumberOfNodes());
- assertEquals(0, cache.getNumberOfAttributes());
-
- cache.stop();
- cache.destroy();
- cache.stop();
- cache.destroy();
- }
-
- public void testFailedStart() throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>(createCache(createConfiguration()));
- registerWrapper(wrapper);
- assertEquals("Correct state", CacheStatus.INSTANTIATED, wrapper.getCacheStatus());
- wrapper.create();
-
- DisruptLifecycleListener listener = new DisruptLifecycleListener();
- listener.setDisrupt(true);
- wrapper.getCache().addCacheListener(listener);
-
- assertEquals("Correct state", CacheStatus.CREATED, wrapper.getCacheStatus());
- try
- {
- wrapper.start();
- fail("Listener did not prevent start");
- }
- catch (CacheException good)
- {
- }
-
- assertEquals("Correct state", CacheStatus.FAILED, wrapper.getCacheStatus());
-
- listener.setDisrupt(false);
-
- wrapper.start();
-
- assertEquals("Correct state", CacheStatus.STARTED, wrapper.getCacheStatus());
-
- wrapper.getCache().put(Fqn.fromString("/a/b/c"), null);
- assertTrue(wrapper.getNumberOfNodes() > 0);
- assertEquals(0, wrapper.getNumberOfAttributes());
-
- listener.setDisrupt(true);
- // need to re-add the listener since the failed start would have nullified the notifier.
- cache.addCacheListener(listener);
-
- try
- {
- wrapper.stop();
- fail("Listener did not prevent stop");
- }
- catch (CacheException good)
- {
- }
-
- assertEquals("Correct state", CacheStatus.FAILED, wrapper.getCacheStatus());
-
- listener.setDisrupt(false);
-
- wrapper.stop();
- assertEquals("Correct state", CacheStatus.STOPPED, wrapper.getCacheStatus());
- wrapper.destroy();
- assertEquals("Correct state", CacheStatus.DESTROYED, wrapper.getCacheStatus());
- }
-
- private String printCacheDetailsTest(boolean html) throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
-
- // have to start the cache before we'll have a root
- cache.start();
- Fqn fqn = Fqn.fromString("/testing/jmx");
- cache.put(fqn, "foobar", "barfoo");
-
- assertEquals("barfoo", cache.get(fqn, "foobar"));
-
- String details = html ? wrapper.printCacheDetailsAsHtml() : wrapper.printCacheDetails();
-
-
- System.out.println("Cache details: " + CachePrinter.printCacheDetails(cache));
- System.out.println("Details: " + details);
-
- assertTrue("Details include testing", details.contains("testing"));
- assertTrue("Details include jmx", details.contains("jmx"));
- assertTrue("Details include foobar", details.contains("foobar"));
- assertTrue("Details include barfoo", details.contains("barfoo"));
-
- return details;
- }
-
- private String printLockInfoTest(boolean html) throws Exception
- {
- Configuration config = createConfiguration();
- config.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
- Cache<String, String> c = createCache(config);
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(c);
-
-// wrapper.setManageCacheLifecycle(true);
- wrapper.create();
- wrapper.start();
-
- TransactionManager tm = config.getRuntimeConfig().getTransactionManager();
-
- tm.begin();
- try
- {
- Fqn fqn = Fqn.fromString("/testing/jmx");
- cache.put(fqn, "foobar", "barfoo");
-
- String locks = html ? wrapper.printLockInfoAsHtml() : wrapper.printLockInfo();
-
- assertTrue("Details include testing", locks.contains("testing"));
- assertTrue("Details include jmx", locks.contains("jmx"));
-
- return locks;
- }
- catch (Exception e)
- {
- tm.setRollbackOnly();
- throw e;
- }
- finally
- {
- tm.commit();
- }
-
- }
-
- private void checkHtml(String html, boolean checkBR)
- {
- if (checkBR)
- assertTrue("Has <br", html.contains("<br"));
-
- assertTrue("No tabs", html.indexOf('\t') == -1);
-
- assertTrue("No spaces", html.indexOf(' ') == -1);
-
- }
-
- @CacheListener
- public class DisruptLifecycleListener
- {
- private boolean disrupt;
-
- @CacheStarted
- public void cacheStarted(Event e)
- {
- if (disrupt) throw new IllegalStateException("I don't want to start");
- }
-
- @CacheStopped
- public void cacheStopped(Event e)
- {
- if (disrupt) throw new IllegalStateException("I don't want to stop");
- }
-
- public void setDisrupt(boolean disrupt)
- {
- this.disrupt = disrupt;
- }
- }
-}
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,171 +0,0 @@
-package org.jboss.cache.jmx;
-
-import org.jboss.cache.Cache;
-import org.jboss.cache.CacheFactory;
-import org.jboss.cache.DefaultCacheFactory;
-import org.jboss.cache.config.Configuration;
-import static org.testng.AssertJUnit.assertFalse;
-import static org.testng.AssertJUnit.assertTrue;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-/**
- * Tests the JMX wrapper class around the cache.
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
- * @author Brian Stansberry
- */
-@Test(groups = "functional")
-public abstract class CacheJmxWrapperTestBase
-{
- public static final String CLUSTER_NAME = "CacheMBeanTest";
-
- protected Cache<String, String> cache;
- protected CacheJmxWrapperMBean<String, String> jmxWrapper;
- protected MBeanServer mBeanServer;
- protected ObjectName mBeanName;
- protected String mBeanNameStr;
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- mBeanServer = MBeanServerFactory.createMBeanServer("CacheMBeanTest");
-
- mBeanNameStr = JmxUtil.PREFIX + CLUSTER_NAME;
- mBeanName = new ObjectName(mBeanNameStr);
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
- try
- {
- cleanup();
- }
- finally
- {
- if (mBeanServer != null)
- {
- MBeanServerFactory.releaseMBeanServer(mBeanServer);
- mBeanServer = null;
- }
- }
- }
-
- protected CacheJmxWrapperMBean<String, String> registerWrapper() throws Exception
- {
- if (cache == null)
- cache = createCache(createConfiguration());
- return registerWrapper(cache);
- }
-
- protected CacheJmxWrapperMBean<String, String> registerWrapper(Cache<String, String> toWrap) throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>(toWrap);
- return registerWrapper(wrapper);
- }
-
- protected CacheJmxWrapperMBean<String, String> registerWrapper(Configuration config) throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>();
- wrapper.setConfiguration(config);
- return registerWrapper(wrapper);
- }
-
- @SuppressWarnings("unchecked")
- protected CacheJmxWrapperMBean<String, String> registerWrapper(CacheJmxWrapperMBean<String, String> wrapper) throws Exception
- {
- JmxUtil.registerCacheMBean(mBeanServer, wrapper, mBeanNameStr);
- jmxWrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
- return jmxWrapper;
- }
-
- protected void unregisterWrapper() throws Exception
- {
- mBeanServer.unregisterMBean(mBeanName);
- }
-
- protected CacheJmxWrapper<String, String> createWrapper(Configuration config)
- {
- CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>();
- wrapper.setConfiguration(config);
- return wrapper;
- }
-
- protected Cache<String, String> createCache(Configuration config)
- {
- CacheFactory<String, String> factory = new DefaultCacheFactory<String, String>();
- cache = factory.createCache(config, false);
- return cache;
- }
-
- protected Configuration createConfiguration()
- {
- Configuration c = new Configuration();
- c.setClusterName(CLUSTER_NAME);
- c.setExposeManagementStatistics(true);
- c.setCacheMode(Configuration.CacheMode.LOCAL);
- return c;
- }
-
- private void cleanup() throws Exception
- {
- if (cache != null)
- {
- try
- {
- cache.stop();
- }
- catch (Exception ignored)
- {
- }
-
- cache = null;
- }
- if (jmxWrapper != null)
- {
- try
- {
- jmxWrapper.stop();
- jmxWrapper.destroy();
- }
- catch (Exception ignored)
- {
- }
-
- jmxWrapper = null;
- }
-
- if (mBeanServer != null && mBeanName != null && mBeanServer.isRegistered(mBeanName))
- mBeanServer.unregisterMBean(mBeanName);
- }
-
- protected void interceptorRegistrationTest(boolean expectMbeans) throws MalformedObjectNameException, NullPointerException
- {
- interceptorRegistrationTest(mBeanNameStr, expectMbeans);
- }
-
- protected void interceptorRegistrationTest(String baseName, boolean expectMbeans) throws MalformedObjectNameException, NullPointerException
- {
- // should be 3 interceptor MBeans loaded:
- ObjectName[] interceptorMBeanNames = {
- new ObjectName(baseName + JmxUtil.JMX_RESOURCE_KEY + "TxInterceptor"),
- new ObjectName(baseName + JmxUtil.JMX_RESOURCE_KEY + "CacheMgmtInterceptor"),
- };
-
- for (ObjectName n : interceptorMBeanNames)
- {
- if (expectMbeans)
- assertTrue(n + " should be registered", mBeanServer.isRegistered(n));
- else
- assertFalse(n + " should not be registered", mBeanServer.isRegistered(n));
- }
- }
-}
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,384 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-package org.jboss.cache.jmx;
-
-import org.jboss.cache.config.Configuration;
-import static org.testng.AssertJUnit.assertTrue;
-import org.testng.annotations.Test;
-
-/**
- * Tests the interceptor registration function of CacheJmxWrapper.
- *
- * @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
- * @version $Revision$
- */
-@Test(groups = "functional")
-public class InterceptorRegistrationTest extends CacheJmxWrapperTestBase
-{
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * cache.start();
- * wrapper creation and registration.
- *
- * @throws Exception
- */
- public void testInterceptorMBeans1() throws Exception
- {
- // have to start the cache to have any interceptors
- createCache(createConfiguration());
- cache.start();
-
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cache);
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- interceptorRegistrationTest(true);
-
- // These should be ignored because we
- // never did wrapper.create()/start()
- wrapper.stop();
- wrapper.destroy();
-
- // Should still be registered
- interceptorRegistrationTest(true);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * cache.start();
- * wrapper creation and and start
- * wrapper registration.
- *
- * @throws Exception
- */
- public void testInterceptorMBeans2() throws Exception
- {
- // have to start the cache to have any interceptors
- createCache(createConfiguration());
- cache.start();
-
- CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>(cache);
- wrapper.start();
- wrapper = registerWrapper(wrapper);
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- interceptorRegistrationTest(true);
-
- wrapper.stop();
- wrapper.destroy();
-
- // Should still no longer be registered
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * Cache not injected
- * wrapper registered;
- * wrapper created and started.
- *
- * @throws Exception
- */
- public void testInterceptorMBeans3() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(createConfiguration());
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- // have to start the cache to have any interceptors
- wrapper.create();
- wrapper.start();
-
- interceptorRegistrationTest(true);
-
- wrapper.stop();
- wrapper.destroy();
-
- // Destroy should unregister if we are managing
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * Cache not injected
- * wrapper created and started.
- * wrapper registered
- *
- * @throws Exception
- */
- public void testInterceptorMBeans4() throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
-
- // have to start the cache to have any interceptors
- wrapper.create();
- wrapper.start();
-
- registerWrapper(wrapper);
-
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- interceptorRegistrationTest(true);
-
- wrapper.stop();
- wrapper.destroy();
-
- // Destroy should unregister if we are managing
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * cache constructed;
- * wrapper constructed and registered with manageCacheLifecycle=true
- * wrapper created and started
- *
- * @throws Exception
- */
- public void testInterceptorMBeans5() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
-// wrapper.setManageCacheLifecycle(true);
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- // have to start the cache to have any interceptors
- wrapper.create();
- wrapper.start();
-
- interceptorRegistrationTest(true);
-
- wrapper.stop();
- wrapper.destroy();
-
- // Destroy should unregister if we are managing
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * cache constructed;
- * wrapper constructed and registered
- * wrapper created and started
- *
- * @throws Exception
- */
- public void testInterceptorMBeans6() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- // have to start the cache to have any interceptors
- wrapper.create();
- wrapper.start();
-
- interceptorRegistrationTest(true);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Confirms interceptor mbeans are registered if the following events
- * occur:
- * <p/>
- * cache constructed;
- * wrapper created and started
- * wrapper registered
- *
- * @throws Exception
- */
- public void testInterceptorMBeans7() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>(createCache(createConfiguration()));
-
- // have to start the cache to have any interceptors
- wrapper.create();
- wrapper.start();
-
- wrapper = registerWrapper(wrapper);
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- interceptorRegistrationTest(true);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Tests that setting registerInterceptors=false disables interceptor
- * registration when the wrapper is registered before create/start
- * are called.
- *
- * @throws Exception
- */
- public void testRegisterInterceptors1() throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- wrapper.setRegisterJmxResource(false);
-
- registerWrapper(wrapper);
-
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- wrapper.create();
- wrapper.start();
-
- interceptorRegistrationTest(false);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- /**
- * Tests that setting registerInterceptors=false disables interceptor
- * registration when the wrapper is registered after create/start
- * are called.
- *
- * @throws Exception
- */
- public void testRegisterInterceptors2() throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- wrapper.setRegisterJmxResource(false);
-
- wrapper.create();
- wrapper.start();
-
- registerWrapper(wrapper);
-
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- interceptorRegistrationTest(false);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- public void testExposeManagementStatistics1() throws Exception
- {
- Configuration cfg = createConfiguration();
- cfg.setExposeManagementStatistics(false);
-
- CacheJmxWrapper<String, String> wrapper = createWrapper(cfg);
- registerWrapper(cfg);
-
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- wrapper.create();
- wrapper.start();
-
- interceptorRegistrationTest(false);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
- }
-
- public void testExposeManagementStatistics2() throws Exception
- {
- Configuration cfg = createConfiguration();
- cfg.setExposeManagementStatistics(false);
-
- CacheJmxWrapper<String, String> wrapper = createWrapper(cfg);
-
- wrapper.create();
- wrapper.start();
-
- registerWrapper(wrapper);
-
- assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
-
- interceptorRegistrationTest(false);
-
- wrapper.stop();
- wrapper.destroy();
-
- interceptorRegistrationTest(false);
-
- unregisterWrapper();
-
- interceptorRegistrationTest(false);
-
- }
-
-}
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/LegacyConfigurationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/LegacyConfigurationTest.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/LegacyConfigurationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,413 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-package org.jboss.cache.jmx;
-
-import org.jboss.cache.Version;
-import org.jboss.cache.config.BuddyReplicationConfig;
-import org.jboss.cache.config.BuddyReplicationConfig.BuddyLocatorConfig;
-import org.jboss.cache.config.CacheLoaderConfig;
-import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.config.Configuration.CacheMode;
-import org.jboss.cache.config.Configuration.NodeLockingScheme;
-import org.jboss.cache.config.EvictionConfig;
-import org.jboss.cache.config.EvictionRegionConfig;
-import org.jboss.cache.config.RuntimeConfig;
-import org.jboss.cache.config.parsing.XmlConfigHelper;
-import org.jboss.cache.eviction.FIFOConfiguration;
-import org.jboss.cache.eviction.FIFOPolicy;
-import org.jboss.cache.eviction.LRUConfiguration;
-import org.jboss.cache.eviction.LRUPolicy;
-import org.jboss.cache.eviction.MRUConfiguration;
-import org.jboss.cache.eviction.MRUPolicy;
-import org.jboss.cache.loader.FileCacheLoader;
-import org.jboss.cache.loader.SingletonStoreCacheLoader;
-import org.jboss.cache.loader.jdbm.JdbmCacheLoader;
-import org.jboss.cache.lock.IsolationLevel;
-import org.jboss.cache.multiplexer.MultiplexerTestHelper;
-import org.jboss.cache.transaction.BatchModeTransactionManagerLookup;
-import org.jgroups.ChannelFactory;
-import org.jgroups.JChannelFactory;
-import org.jgroups.jmx.JChannelFactoryMBean;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.Test;
-import org.w3c.dom.Element;
-
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.ObjectName;
-import javax.transaction.TransactionManager;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * Test of the CacheLegacyJmxWrapper.
- *
- * @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
- * @version $Revision$
- */
-@Test(groups = "functional")
-public class LegacyConfigurationTest extends CacheJmxWrapperTestBase
-{
- @SuppressWarnings({"deprecation", "unchecked"})
- public void testLocalCache() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper();
- registerWrapper(wrapper);
-
- wrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
-
- wrapper.setBuddyReplicationConfig(getBuddyReplicationConfig());
- wrapper.setCacheLoaderConfig(getCacheLoaderConfig());
- wrapper.setCacheMode("REPL_SYNC");
- wrapper.setClusterName("LocalTest");
- wrapper.setClusterConfig(getClusterConfig());
- wrapper.setEvictionPolicyConfig(getEvictionPolicyConfig());
- wrapper.setFetchInMemoryState(false);
- wrapper.setInitialStateRetrievalTimeout(100);
- wrapper.setInactiveOnStartup(true);
- wrapper.setNodeLockingScheme("OPTIMISTIC");
- wrapper.setIsolationLevel("READ_UNCOMMITTED");
- wrapper.setLockAcquisitionTimeout(200);
- wrapper.setReplicationVersion("1.0.1");
- wrapper.setReplQueueInterval(15);
- wrapper.setReplQueueMaxElements(50);
- wrapper.setSyncReplTimeout(300);
- wrapper.setSyncCommitPhase(true);
- wrapper.setSyncRollbackPhase(true);
- wrapper.setTransactionManagerLookupClass(BatchModeTransactionManagerLookup.class.getName());
- wrapper.setExposeManagementStatistics(false);
- wrapper.setUseRegionBasedMarshalling(true);
- wrapper.setUseReplQueue(true);
-
- Configuration c = wrapper.getConfiguration();
-
- assertEquals("CacheMode", "REPL_SYNC", wrapper.getCacheMode());
- assertEquals("CacheMode", CacheMode.REPL_SYNC, c.getCacheMode());
- assertEquals("ClusterName", "LocalTest", wrapper.getClusterName());
- assertEquals("ClusterName", "LocalTest", c.getClusterName());
- assertEquals("FetchInMemoryState", false, wrapper.getFetchInMemoryState());
- assertEquals("FetchInMemoryState", false, c.isFetchInMemoryState());
- assertEquals("InitialStateRetrievalTimeout", 100, wrapper.getInitialStateRetrievalTimeout());
- assertEquals("InitialStateRetrievalTimeout", 100, c.getStateRetrievalTimeout());
- assertEquals("InactiveOnStartup", true, wrapper.isInactiveOnStartup());
- assertEquals("InactiveOnStartup", true, c.isInactiveOnStartup());
- assertEquals("NodeLockingScheme", "OPTIMISTIC", wrapper.getNodeLockingScheme());
- assertEquals("NodeLockingScheme", NodeLockingScheme.OPTIMISTIC, c.getNodeLockingScheme());
- assertEquals("IsolationLevel", "READ_UNCOMMITTED", wrapper.getIsolationLevel());
- assertEquals("IsolationLevel", IsolationLevel.READ_UNCOMMITTED, c.getIsolationLevel());
- assertEquals("LockAcquisitionTimeout", 200, wrapper.getLockAcquisitionTimeout());
- assertEquals("LockAcquisitionTimeout", 200, c.getLockAcquisitionTimeout());
- assertEquals("ReplicationVersion", "1.0.1", wrapper.getReplicationVersion());
- assertEquals("ReplicationVersion", Version.getVersionShort("1.0.1"), c.getReplicationVersion());
- assertEquals("ReplQueueInterval", 15, wrapper.getReplQueueInterval());
- assertEquals("ReplQueueInterval", 15, c.getReplQueueInterval());
- assertEquals("ReplQueueMaxElements", 50, wrapper.getReplQueueMaxElements());
- assertEquals("ReplQueueMaxElements", 50, c.getReplQueueMaxElements());
- assertEquals("SyncReplTimeout", 300, wrapper.getSyncReplTimeout());
- assertEquals("SyncReplTimeout", 300, c.getSyncReplTimeout());
- assertEquals("SyncCommitPhase", true, wrapper.getSyncCommitPhase());
- assertEquals("SyncCommitPhase", true, c.isSyncCommitPhase());
- assertEquals("SyncRollbackPhase", true, wrapper.getSyncRollbackPhase());
- assertEquals("SyncRollbackPhase", true, c.isSyncRollbackPhase());
- assertEquals("TransactionManagerLookupClass", BatchModeTransactionManagerLookup.class.getName(), wrapper.getTransactionManagerLookupClass());
- assertEquals("TransactionManagerLookupClass", BatchModeTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
- assertEquals("ExposeManagementStatistics", false, wrapper.getExposeManagementStatistics());
- assertEquals("ExposeManagementStatistics", false, c.getExposeManagementStatistics());
- assertEquals("UseRegionBasedMarshalling", true, wrapper.getUseRegionBasedMarshalling());
- assertEquals("UseRegionBasedMarshalling", true, c.isUseRegionBasedMarshalling());
- assertEquals("UseReplQueue", true, wrapper.getUseReplQueue());
- assertEquals("UseReplQueue", true, c.isUseReplQueue());
-
- assertEquals("ClusterConfig", getClusterConfig().toString(), wrapper.getClusterConfig().toString());
-
- assertEquals("BuddyReplicationConfig", getBuddyReplicationConfig().toString(), wrapper.getBuddyReplicationConfig().toString());
- BuddyReplicationConfig brc = c.getBuddyReplicationConfig();
- assertEquals("BR enabled", true, brc.isEnabled());
- assertEquals("BR auto grav", false, brc.isAutoDataGravitation());
- assertEquals("BR remove find", false, brc.isDataGravitationRemoveOnFind());
- assertEquals("BR search backup", false, brc.isDataGravitationSearchBackupTrees());
- assertEquals("BR comm timeout", 600000, brc.getBuddyCommunicationTimeout());
- assertEquals("BR poolname", "testpool", brc.getBuddyPoolName());
- BuddyLocatorConfig blc = brc.getBuddyLocatorConfig();
- assertEquals("BR locator", "org.jboss.cache.buddyreplication.TestBuddyLocator", blc.getBuddyLocatorClass());
- Properties props = blc.getBuddyLocatorProperties();
- assertEquals("BR props", "2", props.get("numBuddies"));
-
- assertEquals("CacheLoaderConfig", getCacheLoaderConfig().toString(), wrapper.getCacheLoaderConfig().toString());
- CacheLoaderConfig clc = c.getCacheLoaderConfig();
- assertEquals("CL passivation", false, clc.isPassivation());
- assertEquals("CL passivation", true, clc.isShared());
- assertEquals("CL preload", "/foo", clc.getPreload());
- List<IndividualCacheLoaderConfig> iclcs = clc.getIndividualCacheLoaderConfigs();
- IndividualCacheLoaderConfig iclc = iclcs.get(0);
- assertEquals("CL0 class", FileCacheLoader.class.getName(), iclc.getClassName());
- assertEquals("CL0 async", false, iclc.isAsync());
- assertEquals("CL0 fetch", true, iclc.isFetchPersistentState());
- assertEquals("CL0 ignore", true, iclc.isIgnoreModifications());
- assertEquals("CL0 purge", true, iclc.isPurgeOnStartup());
- assertEquals("CL0 singleton", true, iclc.getSingletonStoreConfig().isSingletonStoreEnabled());
- assertEquals("CL0 singleton class", SingletonStoreCacheLoader.class.getName(), iclc.getSingletonStoreConfig().getSingletonStoreClass());
- iclc = iclcs.get(1);
- assertEquals("CL1 class", JdbmCacheLoader.class.getName(), iclc.getClassName());
- assertEquals("CL1 async", true, iclc.isAsync());
- assertEquals("CL1 fetch", false, iclc.isFetchPersistentState());
- assertEquals("CL1 ignore", false, iclc.isIgnoreModifications());
- assertEquals("CL1 purge", false, iclc.isPurgeOnStartup());
- assertEquals("CL1 singleton", false, iclc.getSingletonStoreConfig().isSingletonStoreEnabled());
- assertEquals("CL1 singleton class", SingletonStoreCacheLoader.class.getName(), iclc.getSingletonStoreConfig().getSingletonStoreClass());
-
- assertEquals("EvictionPolicyConfig", getEvictionPolicyConfig().toString(), wrapper.getEvictionPolicyConfig().toString());
- EvictionConfig ec = c.getEvictionConfig();
- assertEquals("EC queue size", 20000, ec.getDefaultEventQueueSize());
- assertEquals("EC wakeup", 5000, ec.getWakeupInterval());
- assertEquals("EC default pol", LRUPolicy.class.getName(), ec.getDefaultEvictionPolicyClass());
- List<EvictionRegionConfig> ercs = ec.getEvictionRegionConfigs();
- EvictionRegionConfig erc = ercs.get(0);
- assertEquals("ERC0 name", "/_default_", erc.getRegionName());
- assertEquals("ERC0 queue size", 1000, erc.getEventQueueSize());
- LRUConfiguration lru = (LRUConfiguration) erc.getEvictionPolicyConfig();
- assertEquals("EPC0 pol", LRUPolicy.class.getName(), lru.getEvictionPolicyClass());
- assertEquals("EPC0 maxnodes", 5000, lru.getMaxNodes());
- assertEquals("EPC0 ttl", 1000000, lru.getTimeToLive());
- erc = ercs.get(1);
- assertEquals("ERC1 name", "/org/jboss/data", erc.getRegionName());
- assertEquals("ERC1 queue size", 20000, erc.getEventQueueSize());
- FIFOConfiguration fifo = (FIFOConfiguration) erc.getEvictionPolicyConfig();
- assertEquals("EPC1 pol", FIFOPolicy.class.getName(), fifo.getEvictionPolicyClass());
- assertEquals("EPC1 maxnodes", 5000, fifo.getMaxNodes());
- erc = ercs.get(2);
- assertEquals("ERC2 name", "/test", erc.getRegionName());
- assertEquals("ERC2 queue size", 20000, erc.getEventQueueSize());
- MRUConfiguration mru = (MRUConfiguration) erc.getEvictionPolicyConfig();
- assertEquals("EPC2 pol", MRUPolicy.class.getName(), mru.getEvictionPolicyClass());
- assertEquals("EPC2 maxnodes", 10000, mru.getMaxNodes());
- erc = ercs.get(3);
- assertEquals("ERC3 name", "/maxAgeTest", erc.getRegionName());
- assertEquals("ERC3 queue size", 20000, erc.getEventQueueSize());
- lru = (LRUConfiguration) erc.getEvictionPolicyConfig();
- assertEquals("EPC3 pol", LRUPolicy.class.getName(), lru.getEvictionPolicyClass());
- assertEquals("EPC3 maxnodes", 10000, lru.getMaxNodes());
- assertEquals("EPC3 maxage", 10000, lru.getMaxAge());
- assertEquals("EPC3 ttl", 8000, lru.getTimeToLive());
-
- }
-
- @SuppressWarnings("unchecked")
- public void testRuntimeConfig() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>();
- registerWrapper(wrapper);
-
- wrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
-
- // Fake a TM by making a bogus proxy
- TransactionManager tm = (TransactionManager) Proxy.newProxyInstance(getClass().getClassLoader(),
- new Class[]{TransactionManager.class}, new MockInvocationHandler());
- wrapper.setTransactionManager(tm);
- ChannelFactory cf = new JChannelFactory();
- wrapper.setMuxChannelFactory(cf);
-
- RuntimeConfig rc = wrapper.getConfiguration().getRuntimeConfig();
-
- assertSame("Same TM", tm, wrapper.getTransactionManager());
- assertSame("Same TM", tm, rc.getTransactionManager());
- assertSame("Same ChannelFactory", cf, wrapper.getMuxChannelFactory());
- assertSame("Same ChannelFactory", cf, rc.getMuxChannelFactory());
- }
-
- @SuppressWarnings("unchecked")
- public void testLegacyMuxChannelCreation() throws Exception
- {
- CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>();
- registerWrapper(wrapper);
-
- wrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
- wrapper.setMultiplexerStack(MultiplexerTestHelper.MUX_STACK);
-
- JChannelFactory factory = new JChannelFactory();
- factory.setDomain("jbc.mux.test");
- factory.setExposeChannels(false);
- factory.setMultiplexerConfig(MultiplexerTestHelper.getClusterConfigElement(getDefaultProperties()));
-
- ObjectName on = new ObjectName("jgroups:service=Mux");
- mBeanServer.registerMBean(new org.jgroups.jmx.JChannelFactory(factory), on);
-
- wrapper.setMultiplexerService((JChannelFactoryMBean) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, on, JChannelFactoryMBean.class, false));
-
- wrapper.start();
-
- RuntimeConfig rc = wrapper.getConfiguration().getRuntimeConfig();
- assertNotNull("Channel created", rc.getChannel());
- }
-
- protected static Element getBuddyReplicationConfig() throws Exception
- {
-
- String xmlStr =
- " <buddy enabled=\"true\" poolName=\"testpool\" communicationTimeout=\"600000\">\n" +
- " <dataGravitation auto=\"false\" removeOnFind=\"false\" searchBackupTrees=\"false\"/>\n" +
- " <locator class=\"org.jboss.cache.buddyreplication.TestBuddyLocator\">\n" +
- " <properties>\n" +
- " numBuddies = 2\n" +
- " </properties>\n" +
- " </locator>\n" +
- " </buddy>";
- return XmlConfigHelper.stringToElement(xmlStr);
- }
-
- protected static Element getCacheLoaderConfig() throws Exception
- {
- String xmlStr =
- " <loaders passivation=\"false\" shared=\"true\">\n" +
- " <preload>\n" +
- " <node fqn=\"/foo\"/>\n" +
- " </preload>\n" +
- " <loader class=\"org.jboss.cache.loader.FileCacheLoader\" async=\"false\" fetchPersistentState=\"true\"\n" +
- " ignoreModifications=\"true\" purgeOnStartup=\"true\">\n" +
- " <properties>\n" +
- " location=/tmp\n " +
- " </properties>\n" +
- " <singletonStore enabled=\"true\" /> \n" +
- " </loader>\n" +
- " <loader class=\"org.jboss.cache.loader.jdbm.JdbmCacheLoader\" async=\"true\" fetchPersistentState=\"false\"\n" +
- " ignoreModifications=\"false\" purgeOnStartup=\"false\">\n" +
- " <properties>\n" +
- " location=/home/bstansberry\n" +
- " </properties>\n" +
- " <singletonStore enabled=\"false\" /> \n" +
- " </loader>\n" +
- " </loaders>";
- return XmlConfigHelper.stringToElement(xmlStr);
- }
-
- protected static Element getEvictionPolicyConfig() throws Exception
- {
-
- String xmlStr =
- " <eviction wakeUpInterval=\"5000\" defaultPolicyClass=\"org.jboss.cache.eviction.LRUPolicy\" defaultEventQueueSize=\"20000\">\n" +
- " <default eventQueueSize=\"1000\">\n" +
- " <attribute name=\"maxNodes\">5000</attribute>\n" +
- " <attribute name=\"timeToLive\">1000000</attribute>\n" +
- " </default>\n" +
- "<region name=\"/org/jboss/data\" policyClass=\"org.jboss.cache.eviction.FIFOPolicy\">\n" +
- " <attribute name=\"maxNodes\">5000</attribute>\n" +
- "</region>\n" +
- "<region name=\"/test/\" policyClass=\"org.jboss.cache.eviction.MRUPolicy\">\n" +
- " <attribute name=\"maxNodes\">10000</attribute>\n" +
- "</region>\n" +
- "<region name=\"/maxAgeTest/\">\n" +
- " <attribute name=\"maxNodes\">10000</attribute>\n" +
- " <attribute name=\"timeToLiveSeconds\">8</attribute>\n" +
- " <attribute name=\"maxAgeSeconds\">10</attribute>\n" +
- "</region>\n" +
- " </eviction>";
- return XmlConfigHelper.stringToElement(xmlStr);
- }
-
- protected static Element getClusterConfig() throws Exception
- {
- String xml =
- "<jgroupsConfig>\n" +
- "<UDP mcast_addr=\"228.10.10.10\"\n" +
- " mcast_port=\"45588\"\n" +
- " tos=\"8\"\n" +
- " ucast_recv_buf_size=\"20000000\"\n" +
- " ucast_send_buf_size=\"640000\"\n" +
- " mcast_recv_buf_size=\"25000000\"\n" +
- " mcast_send_buf_size=\"640000\"\n" +
- " loopback=\"false\"\n" +
- " discard_incompatible_packets=\"true\"\n" +
- " max_bundle_size=\"64000\"\n" +
- " max_bundle_timeout=\"30\"\n" +
- " use_incoming_packet_handler=\"true\"\n" +
- " ip_ttl=\"2\"\n" +
- " enable_bundling=\"false\"\n" +
- " enable_diagnostics=\"true\"\n" +
- " use_concurrent_stack=\"true\"\n" +
- " thread_naming_pattern=\"pl\"\n" +
- " thread_pool.enabled=\"true\"\n" +
- " thread_pool.min_threads=\"1\"\n" +
- " thread_pool.max_threads=\"25\"\n" +
- " thread_pool.keep_alive_time=\"30000\"\n" +
- " thread_pool.queue_enabled=\"true\"\n" +
- " thread_pool.queue_max_size=\"10\"\n" +
- " thread_pool.rejection_policy=\"Run\"\n" +
- " oob_thread_pool.enabled=\"true\"\n" +
- " oob_thread_pool.min_threads=\"1\"\n" +
- " oob_thread_pool.max_threads=\"4\"\n" +
- " oob_thread_pool.keep_alive_time=\"10000\"\n" +
- " oob_thread_pool.queue_enabled=\"true\"\n" +
- " oob_thread_pool.queue_max_size=\"10\"\n" +
- " oob_thread_pool.rejection_policy=\"Run\"/>\n" +
- " <PING timeout=\"2000\" num_initial_members=\"3\"/>\n" +
- " <MERGE2 max_interval=\"30000\" min_interval=\"10000\"/>\n" +
- " <FD_SOCK/>\n" +
- " <FD timeout=\"10000\" max_tries=\"5\" shun=\"true\"/>\n" +
- " <VERIFY_SUSPECT timeout=\"1500\"/>\n" +
- " <pbcast.NAKACK max_xmit_size=\"60000\"\n" +
- " use_mcast_xmit=\"false\" gc_lag=\"0\"\n" +
- " retransmit_timeout=\"300,600,1200,2400,4800\"\n" +
- " discard_delivered_msgs=\"true\"/>\n" +
- " <UNICAST timeout=\"300,600,1200,2400,3600\"/>\n" +
- " <pbcast.STABLE stability_delay=\"1000\" desired_avg_gossip=\"50000\"\n" +
- " max_bytes=\"400000\"/>\n" +
- " <pbcast.GMS print_local_addr=\"true\" join_timeout=\"5000\"\n" +
- " join_retry_timeout=\"2000\" shun=\"false\"\n" +
- " view_bundling=\"true\" view_ack_collection_timeout=\"5000\"/>\n" +
- " <FRAG2 frag_size=\"60000\"/>\n" +
- " <pbcast.STREAMING_STATE_TRANSFER use_reading_thread=\"true\"/>\n" +
- " <pbcast.FLUSH timeout=\"0\"/>\n" +
- "</jgroupsConfig>";
- return XmlConfigHelper.stringToElement(xml);
- }
-
- protected String getDefaultProperties()
- {
- return "UDP(mcast_addr=224.0.0.36;mcast_port=55566;ip_ttl=32;" +
- "mcast_send_buf_size=150000;mcast_recv_buf_size=80000):" +
- "PING(timeout=1000;num_initial_members=2):" +
- "MERGE2(min_interval=5000;max_interval=10000):" +
- "FD_SOCK:" +
- "VERIFY_SUSPECT(timeout=1500):" +
- "pbcast.NAKACK(gc_lag=50;max_xmit_size=8192;retransmit_timeout=600,1200,2400,4800):" +
- "UNICAST(timeout=600,1200,2400,4800):" +
- "pbcast.STABLE(desired_avg_gossip=20000):" +
- "FRAG(frag_size=8192;down_thread=false;up_thread=false):" +
- "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
- "shun=false;print_local_addr=true):" +
- "pbcast.STATE_TRANSFER";
- }
-
- class MockInvocationHandler implements InvocationHandler
- {
-
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
- {
- return null;
- }
-
- }
-}
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/LifecycleNotificationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/LifecycleNotificationTest.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/LifecycleNotificationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,102 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2006, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-package org.jboss.cache.jmx;
-
-import static org.testng.AssertJUnit.assertEquals;
-
-import javax.management.AttributeChangeNotification;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import java.util.LinkedList;
-import java.util.List;
-
-/**
- * A LifecycleNotificationTest.
- *
- * @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
- * @version $Revision$
- */
-public class LifecycleNotificationTest extends CacheJmxWrapperTestBase
-{
- public void testGetStateAndStateNotification() throws Exception
- {
- CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- StateNotificationListener listener = new StateNotificationListener();
- wrapper.addNotificationListener(listener, null, null);
-
- assertEquals("Correct state after instanitation",
- CacheJmxWrapperMBean.UNREGISTERED, wrapper.getState());
-
- registerWrapper(wrapper);
- assertEquals("Correct state after registration",
- CacheJmxWrapperMBean.REGISTERED, wrapper.getState());
-
- wrapper.create();
- assertEquals("Correct state after create",
- CacheJmxWrapperMBean.CREATED, wrapper.getState());
-
- wrapper.start();
- assertEquals("Correct state after start",
- CacheJmxWrapperMBean.STARTED, wrapper.getState());
-
- wrapper.stop();
- assertEquals("Correct state after stop",
- CacheJmxWrapperMBean.STOPPED, wrapper.getState());
-
- wrapper.destroy();
- assertEquals("Correct state after destroy",
- CacheJmxWrapperMBean.DESTROYED, wrapper.getState());
-
- unregisterWrapper();
- assertEquals("Correct state after unregistration",
- CacheJmxWrapperMBean.UNREGISTERED, wrapper.getState());
-
- System.out.println(listener.notifications);
- assertEquals("Correct number of notifications received", 4, listener.notifications.size());
- assertEquals("Correct first notification", new Integer(CacheJmxWrapperMBean.STARTING), listener.notifications.get(0));
- assertEquals("Correct second notification", new Integer(CacheJmxWrapperMBean.STARTED), listener.notifications.get(1));
- assertEquals("Correct third notification", new Integer(CacheJmxWrapperMBean.STOPPING), listener.notifications.get(2));
- assertEquals("Correct fourth notification", new Integer(CacheJmxWrapperMBean.STOPPED), listener.notifications.get(3));
- }
-
- private static class StateNotificationListener
- implements NotificationListener
- {
- private List<Integer> notifications = new LinkedList<Integer>();
-
- public void handleNotification(Notification msg, Object handback)
- {
- if (msg instanceof AttributeChangeNotification)
- {
- AttributeChangeNotification change = (AttributeChangeNotification) msg;
- String attrName = change.getAttributeName();
- Object newValue = change.getNewValue();
- if ("State".equals(attrName) && newValue != null && newValue instanceof Integer)
- {
- notifications.add((Integer) newValue);
- }
- }
- }
- }
-
-}
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/NotificationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/NotificationTest.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/NotificationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,467 +0,0 @@
-package org.jboss.cache.jmx;
-
-import org.jboss.cache.CacheFactory;
-import org.jboss.cache.CacheSPI;
-import org.jboss.cache.DefaultCacheFactory;
-import org.jboss.cache.Fqn;
-import org.jboss.cache.config.CacheLoaderConfig;
-import org.jboss.cache.config.Configuration;
-import org.jboss.cache.config.Configuration.CacheMode;
-import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
-import org.jboss.cache.loader.CacheLoader;
-import static org.testng.AssertJUnit.*;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import javax.management.MBeanServer;
-import javax.management.MBeanServerFactory;
-import javax.management.Notification;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import java.util.EnumSet;
-import java.util.HashMap;
-
-/**
- * Functional tests for CacheJmxWrapper broadcast of cache event notifications
- *
- * @author Jerry Gauthier
- * @version $Id$
- */
-@Test(groups = {"functional"})
-public class NotificationTest
-{
- protected static final String CLUSTER_NAME = "NotificationTestCluster";
-
- protected static final String CAPITAL = "capital";
- protected static final String CURRENCY = "currency";
- protected static final String POPULATION = "population";
- protected static final String EUROPE_NODE = "Europe";
-
- public enum Type
- {
- STARTED, STOPPED, PRECREATE, POSTCREATE, PREEVICT, POSTEVICT,
- PRELOAD, POSTLOAD, PREREMOVE, POSTREMOVE, PREVISIT, POSTVISIT,
- PREMODIFY, POSTMODIFY, PREACTIVATE, POSTACTIVATE, PREPASSIVATE,
- POSTPASSIVATE, VIEWCHANGE
- }
-
- protected MBeanServer m_server;
- protected EnumSet<Type> events = EnumSet.noneOf(Type.class);
-
- protected CacheSPI<Object, Object> cache = null;
- protected boolean optimistic = false;
-
- @BeforeMethod(alwaysRun = true)
- public void setUp() throws Exception
- {
- m_server = MBeanServerFactory.createMBeanServer();
-
- Object cacheMBean = createCacheAndJmxWrapper();
-
- // bind manually for now.
- ObjectName mgmt = getWrapperObjectName();
-
- m_server.registerMBean(cacheMBean, mgmt);
- }
-
- protected Object createCacheAndJmxWrapper() throws Exception
- {
- cache = createCache(CLUSTER_NAME);
- return new CacheJmxWrapper<Object, Object>(cache);
- }
-
- @AfterMethod(alwaysRun = true)
- public void tearDown() throws Exception
- {
- try
- {
- cleanup();
- }
- finally
- {
- // make sure we stop the mbean server
- if (m_server != null)
- MBeanServerFactory.releaseMBeanServer(m_server);
- }
- }
-
- protected void cleanup() throws Exception
- {
- events.clear();
-
- destroyCache();
-
- if (m_server != null)
- {
- ObjectName mgmt = getWrapperObjectName();
- if (m_server.isRegistered(mgmt))
- m_server.unregisterMBean(mgmt);
- }
- }
-
- protected void destroyCache()
- {
- if (cache != null)
- {
- // stop the cache before the listener is unregistered
- //cache1.stop();
- cache.destroy();
- cache = null;
- }
- }
-
- protected ObjectName getWrapperObjectName() throws Exception
- {
- return new ObjectName(JmxUtil.PREFIX + CLUSTER_NAME);
- }
-
- public void testNotifications() throws Exception
- {
- assertNotNull("MBeanServer is null.", m_server);
- assertNotNull("Cache is null.", cache);
-
- ObjectName mgmt = getWrapperObjectName();
- MyListener listener = new MyListener(mgmt);
-
-
- m_server.addNotificationListener(mgmt, listener, null, null);
-
- // start the cache after registering listener - this will trigger CacheStarted
- // since cache is defined with cluster, thiswill also trigger ViewChange
- cache.start();
-
- // add a node - this will trigger NodeCreated, NodeModify(pre/post) and NodeModified
- HashMap<Object, Object> albania = new HashMap<Object, Object>(4);
- albania.put(CAPITAL, "Tirana");
- albania.put(CURRENCY, "Lek");
- cache.put("Europe/Albania", albania);
-
- // modify a node - this will trigger NodeModified and NodeModify(pre/post)
- cache.put("Europe/Albania", POPULATION, 3563112);
-
- // retrieve an attribute - this will trigger NodeVisited
- Fqn key = Fqn.fromString("Europe/Albania");
- assertNotNull("Retrieval error: expected to retrieve " + CURRENCY + " for " + key, cache.get(key, CURRENCY));
-
- // evict the node - this will trigger NodePassivate, NodeEvicted and NodeEvict(pre/post)
- cache.evict(key);
-
- // retrieve the attribute again - this will trigger NodeVisited and NodeActivate
- assertNotNull("Retrieval error: expected to retrieve " + CURRENCY + " for " + key, cache.get(key, CURRENCY));
-
- // remove the node - this will trigger NodeRemoved and NodeRemove(pre/post)
- cache.removeNode(key);
-
- // clean up before stopping the cache
- CacheLoader cl = cache.getCacheLoaderManager().getCacheLoader();
- cl.remove(Fqn.fromString(EUROPE_NODE));
-
- // stop the cache
- cache.stop();
- m_server.removeNotificationListener(mgmt, listener);
-
- // run the tests
- assertTrue("Expected CacheStarted notification", events.contains(Type.STARTED));
- assertTrue("Expected CacheStopped notification", events.contains(Type.STOPPED));
- assertTrue("Expected NodeCreated notification", events.contains(Type.PRECREATE));
- assertTrue("Expected NodeCreated notification", events.contains(Type.POSTCREATE));
- assertTrue("Expected NodeEvicted notification", events.contains(Type.PREEVICT));
- assertTrue("Expected NodeEvicted notification", events.contains(Type.POSTEVICT));
- assertTrue("Expected NodeLoaded notification", events.contains(Type.PRELOAD));
- assertTrue("Expected NodeLoaded notification", events.contains(Type.POSTLOAD));
- assertTrue("Expected NodeVisited notification", events.contains(Type.PREVISIT));
- assertTrue("Expected NodeVisited notification", events.contains(Type.POSTVISIT));
- assertTrue("Expected NodeActivated notification", events.contains(Type.PREACTIVATE));
- assertTrue("Expected NodeActivated notification", events.contains(Type.POSTACTIVATE));
- assertTrue("Expected NodeModified notification", events.contains(Type.PREMODIFY));
- assertTrue("Expected NodeModified notification", events.contains(Type.POSTMODIFY));
- assertTrue("Expected NodePassivated notification", events.contains(Type.PREPASSIVATE));
- assertTrue("Expected NodePassivated notification", events.contains(Type.POSTPASSIVATE));
- assertTrue("Expected NodeRemoved notification", events.contains(Type.PREREMOVE));
- assertTrue("Expected NodeRemoved notification", events.contains(Type.POSTREMOVE));
- assertTrue("Expected ViewChange notification", events.contains(Type.VIEWCHANGE));
- validateHealthyListener(listener);
- }
-
- public void testEarlyRegistration() throws Exception
- {
- // undo setup
- cleanup();
-
- CacheJmxWrapper<Object, Object> wrapper = new CacheJmxWrapper<Object, Object>();
- ObjectName mgmt = getWrapperObjectName();
- m_server.registerMBean(wrapper, mgmt);
- MyListener listener = new MyListener(mgmt);
- m_server.addNotificationListener(mgmt, listener, null, null);
-
- cache = createCache(CLUSTER_NAME);
- wrapper.setCache(cache);
- cache.start();
- try
- {
- assertTrue("Expected CacheStarted notification", events.contains(Type.STARTED));
- validateHealthyListener(listener);
- }
- finally
- {
- cache.stop();
- }
- }
-
- public void testLateRegistration() throws Exception
- {
- assertNotNull("MBeanServer is null.", m_server);
- assertNotNull("Cache is null.", cache);
-
- // start the cache before registering listener
- cache.start();
-
- try
- {
- ObjectName mgmt = getWrapperObjectName();
- MyListener listener = new MyListener(mgmt);
-
- m_server.addNotificationListener(mgmt, listener, null, null);
-
- // add a node - this will trigger NodeCreated, NodeModify(pre/post) and NodeModified
- HashMap<Object, Object> albania = new HashMap<Object, Object>(4);
- albania.put(CAPITAL, "Tirana");
- albania.put(CURRENCY, "Lek");
- cache.put("Europe/Albania", albania);
-
- // run the tests
- assertTrue("Expected NodeModified notification", events.contains(Type.PREMODIFY));
- assertTrue("Expected NodeModified notification", events.contains(Type.POSTMODIFY));
- validateHealthyListener(listener);
- }
- finally
- {
- cache.stop();
- }
- }
-
- public void testListenerRemoval() throws Exception
- {
- assertNotNull("MBeanServer is null.", m_server);
- assertNotNull("Cache is null.", cache);
-
- ObjectName mgmt = getWrapperObjectName();
- MyListener listener = new MyListener(mgmt);
-
- m_server.addNotificationListener(mgmt, listener, null, null);
-
- // start the cache after registering listener - this will trigger CacheStarted
- // since cache is defined with cluster, thiswill also trigger ViewChange
- cache.start();
- boolean ok = false;
- try
- {
- assertTrue("Expected CacheStarted notification", events.contains(Type.STARTED));
-
- m_server.removeNotificationListener(mgmt, listener);
- ok = true;
- }
- finally
- {
- cache.stop();
- if (ok)
- {
- assertFalse("Expected no CacheStopped notification", events.contains(Type.STOPPED));
- validateHealthyListener(listener);
- }
- }
- }
-
- private CacheSPI<Object, Object> createCache(String clusterName) throws Exception
- {
- Configuration config = createConfiguration(clusterName);
- CacheFactory<Object, Object> factory = new DefaultCacheFactory<Object, Object>();
- CacheSPI<Object, Object> cache = (CacheSPI<Object, Object>) factory.createCache(config, false);
-
- cache.create();
- // start the cache after the listener has been registered
- //cache.start();
- return cache;
- }
-
- protected Configuration createConfiguration(String clusterName) throws Exception
- {
- Configuration config = UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.REPL_SYNC);
- config.setCacheMode(Configuration.CacheMode.REPL_SYNC);
- config.setCacheLoaderConfig(getCacheLoaderConfig("location=" + getTempDir()));
- config.setExposeManagementStatistics(true);
- config.setClusterName(clusterName);
- if (optimistic)
- {
- config.setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
- config.setNodeLockingScheme("OPTIMISTIC");
- }
-
- return config;
- }
-
- private static String getTempDir()
- {
- return System.getProperty("java.io.tempdir", "/tmp");
- }
-
- private static boolean getPre(Object data)
- {
- assertNotNull("User data is null, should be Object[]", data);
- assertTrue("User data is " + data.getClass().getName() + ", should be Object[]", data instanceof Object[]);
-
- Object[] parms = (Object[]) data;
- assertTrue("Parameter is " + parms[1].getClass().getName() + ", should be Boolean", parms[1] instanceof Boolean);
- return (Boolean) parms[1];
- }
-
- protected static CacheLoaderConfig getCacheLoaderConfig(String properties) throws Exception
- {
- return UnitTestCacheConfigurationFactory.buildSingleCacheLoaderConfig(true, "",
- "org.jboss.cache.loader.FileCacheLoader", properties, false, false, true, false, false);
- }
-
- private static void validateHealthyListener(MyListener listener)
- {
- if (listener.failure != null)
- throw listener.failure;
- if (listener.exception != null)
- throw listener.exception;
- }
-
- private class MyListener implements NotificationListener
- {
- private RuntimeException exception;
- private AssertionError failure;
- private final String emitterObjectName;
-
- MyListener(ObjectName emitter)
- {
- this.emitterObjectName = emitter.getCanonicalName();
- }
-
- public void handleNotification(Notification notification, Object handback)
- {
- try
- {
- String type = notification.getType();
- Object userData = notification.getUserData();
-
- if (type.equals(CacheNotificationBroadcaster.NOTIF_CACHE_STARTED))
- {
- events.add(Type.STARTED);
- assertEquals("Correct object name in start notification", emitterObjectName, userData);
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_CACHE_STOPPED))
- {
- events.add(Type.STOPPED);
- assertEquals("Correct object name in stop notification", emitterObjectName, userData);
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_CREATED))
- {
- if (getPre(userData))
- {
- events.add(Type.PRECREATE);
- }
- else
- {
- events.add(Type.POSTCREATE);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_EVICTED))
- {
- if (getPre(userData))
- {
- events.add(Type.PREEVICT);
- }
- else
- {
- events.add(Type.POSTEVICT);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_LOADED))
- {
- if (getPre(userData))
- {
- events.add(Type.PRELOAD);
- }
- else
- {
- events.add(Type.POSTLOAD);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_REMOVED))
- {
- if (getPre(userData))
- {
- events.add(Type.PREREMOVE);
- }
- else
- {
- events.add(Type.POSTREMOVE);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_VISITED))
- {
- if (getPre(userData))
- {
- events.add(Type.PREVISIT);
- }
- else
- {
- events.add(Type.POSTVISIT);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_VIEW_CHANGED))
- {
- events.add(Type.VIEWCHANGE);
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_ACTIVATED))
- {
- if (getPre(userData))
- {
- events.add(Type.PREACTIVATE);
- }
- else
- {
- events.add(Type.POSTACTIVATE);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_MODIFIED))
- {
- if (getPre(userData))
- {
- events.add(Type.PREMODIFY);
- }
- else
- {
- events.add(Type.POSTMODIFY);
- }
- }
- else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_PASSIVATED))
- {
- if (getPre(userData))
- {
- events.add(Type.PREPASSIVATE);
- }
- else
- {
- events.add(Type.POSTPASSIVATE);
- }
- }
- }
- catch (RuntimeException e)
- {
- // Store so the test can rethrow
- exception = e;
- }
- catch (AssertionError e)
- {
- // Store so the test can rethrow
- failure = e;
- }
- }
- }
-
-}
Deleted: core/trunk/src/test/java/org/jboss/cache/jmx/OptimisticNotificationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/OptimisticNotificationTest.java 2008-08-08 15:15:14 UTC (rev 6545)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/OptimisticNotificationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -1,19 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- *
- * Distributable under LGPL license.
- * See terms of license at gnu.org.
- */
-package org.jboss.cache.jmx;
-
-
-/**
- * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
- */
-public class OptimisticNotificationTest extends NotificationTest
-{
- public OptimisticNotificationTest()
- {
- optimistic = true;
- }
-}
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,456 @@
+package org.jboss.cache.jmx.deprecated;
+
+import org.jboss.cache.Cache;
+import org.jboss.cache.CacheException;
+import org.jboss.cache.CacheStatus;
+import org.jboss.cache.Fqn;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import org.jboss.cache.jmx.JmxRegistrationManager;
+import org.jboss.cache.jmx.CacheJmxWrapperMBean;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.Configuration.CacheMode;
+import org.jboss.cache.notifications.annotation.CacheListener;
+import org.jboss.cache.notifications.annotation.CacheStarted;
+import org.jboss.cache.notifications.annotation.CacheStopped;
+import org.jboss.cache.notifications.event.Event;
+import org.jboss.cache.transaction.DummyTransactionManagerLookup;
+import org.jboss.cache.util.CachePrinter;
+import org.jboss.cache.util.TestingUtil;
+import org.jgroups.Address;
+import org.jgroups.stack.IpAddress;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.Test;
+
+import javax.management.ObjectName;
+import javax.transaction.TransactionManager;
+import java.util.List;
+
+/**
+ * Tests the JMX wrapper class around the cache.
+ *
+ * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
+ * @author Brian Stansberry
+ */
+@Test(groups = "functional")
+public class CacheJmxWrapperTest extends CacheJmxWrapperTestBase
+{
+ public void testCacheMBeanBinding() throws Exception
+ {
+ registerWrapper();
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+ }
+
+ public void testSetCacheObjectName() throws Exception
+ {
+ ObjectName on = new ObjectName("jboss.cache:test=SetCacheObjectName");
+ boolean registered = false;
+ try
+ {
+ CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
+ wrapper.setCacheObjectName(on.getCanonicalName());
+
+ // Register under the standard name
+ registerWrapper(wrapper);
+ // Should be registered under 'on'
+ registered = mBeanServer.isRegistered(on);
+
+ assertTrue("Registered with configured name", registered);
+ assertEquals("Configured name retained", on.getCanonicalName(), wrapper.getCacheObjectName());
+
+ wrapper.create();
+ wrapper.start();
+
+ interceptorRegistrationTest(on.getCanonicalName(), true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+ }
+ finally
+ {
+ if (registered)
+ mBeanServer.unregisterMBean(on);
+ }
+ }
+
+ public void testGetCacheObjectName() throws Exception
+ {
+ ObjectName on = new ObjectName("jboss.cache:test=SetCacheObjectName");
+ String str = on.getCanonicalName();
+ CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
+ wrapper.setCacheObjectName(str);
+
+ assertEquals("Setter and getter match", str, wrapper.getCacheObjectName());
+
+ // Go back to the default
+ wrapper.setCacheObjectName(null);
+ assertEquals("Got default ObjectName", JmxRegistrationManager.CLUSTERED_CACHE_PREFIX + CLUSTER_NAME, wrapper.getCacheObjectName());
+
+ registerWrapper(wrapper);
+ assertEquals("Returns standard name", mBeanName, new ObjectName(wrapper.getCacheObjectName()));
+ }
+
+ public void testGetConfiguration1() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
+ Configuration cfgFromJmx = wrapper.getConfiguration();
+ assertNotNull("Got a configuration", cfgFromJmx);
+ assertSame(cache.getConfiguration(), cfgFromJmx);
+ }
+
+ public void testGetConfiguration2() throws Exception
+ {
+ Configuration cfg = createConfiguration();
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cfg);
+ Configuration cfgFromJmx = wrapper.getConfiguration();
+ assertNotNull("Got a configuration", cfgFromJmx);
+ assertSame(cfg, cfgFromJmx);
+ }
+
+ /**
+ * Note that this is a bit of a 'white box' test as it assumes that the
+ * returned String equals Configuration.toString(). That could change and
+ * break this test; if it does, and there's nothing wrong with the
+ * change, just modify the test.
+ *
+ * @throws Exception
+ */
+ public void testPrintConfigurationAsString1() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
+ String cfgFromJmx = wrapper.printConfigurationAsString();
+ assertEquals(cache.getConfiguration().toString(), cfgFromJmx);
+ }
+
+ /**
+ * Note that this is a bit of a 'white box' test as it assumes that the
+ * returned String equals Configuration.toString(). That could change and
+ * break this test; if it does, and there's nothing wrong with the
+ * change, just modify the test.
+ *
+ * @throws Exception
+ */
+ public void testPrintConfigurationAsString2() throws Exception
+ {
+ Configuration cfg = createConfiguration();
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cfg);
+ wrapper.create();
+ wrapper.start();
+ String cfgFromJmx = wrapper.printConfigurationAsString();
+ assertEquals(wrapper.getCache().getConfiguration().toString(), cfgFromJmx);
+ }
+
+ /**
+ * Note that this is a bit of a 'white box' test as it checks
+ * the currently coded HTML format and assumes that the HTML content is
+ * derived from Configuration.toString(). That could change and break
+ * this test; if it does, and there's nothing wrong with the
+ * change, just modify the test.
+ *
+ * @throws Exception
+ */
+ public void testPrintConfigurationAsHtml1() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
+ String cfgFromJmx = wrapper.printConfigurationAsHtmlString();
+ assertEquals(CacheJmxWrapper.formatHtml(cache.getConfiguration().toString()), cfgFromJmx);
+ checkHtml(cfgFromJmx, false);
+ }
+
+ /**
+ * Note that this is a bit of a 'white box' test as it checks
+ * the currently coded HTML format and assumes that the HTML content is
+ * derived from Configuration.toString(). That could change and break
+ * this test; if it does, and there's nothing wrong with the
+ * change, just modify the test.
+ *
+ * @throws Exception
+ */
+ public void testPrintConfigurationAsHtml2() throws Exception
+ {
+ Configuration cfg = createConfiguration();
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cfg);
+ wrapper.create();
+ wrapper.start();
+ String cfgFromJmx = wrapper.printConfigurationAsHtmlString();
+ assertEquals(CacheJmxWrapper.formatHtml(wrapper.getCache().getConfiguration().toString()), cfgFromJmx);
+ checkHtml(cfgFromJmx, false);
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testGetCache() throws Exception
+ {
+ registerWrapper();
+ // have to start the cache before we'll have a root
+ cache.start();
+
+ Cache<String, String> cacheJmx = (Cache<String, String>) mBeanServer.getAttribute(mBeanName, "Cache");
+ cacheJmx.getRoot().put("key", "value");
+
+ assertEquals("value", cache.getRoot().get("key"));
+
+ Fqn fqn = Fqn.fromString("/testing/jmx");
+ cache.put(fqn, "key", "value");
+
+ assertEquals("value", cacheJmx.get(fqn, "key"));
+ }
+
+ public void testPrintCacheDetails() throws Exception
+ {
+ printCacheDetailsTest(false);
+ }
+
+ /**
+ * Note that this is a bit of a 'white box' test as it checks
+ * the currently coded HTML format. That could change and break
+ * this test; if it does, and there's nothing wrong with the
+ * change, just modify the test.
+ *
+ * @throws Exception
+ */
+ public void testPrintCacheDetailsAsHtml() throws Exception
+ {
+ String html = printCacheDetailsTest(true);
+ checkHtml(html, true);
+ }
+
+ public void testPrintLockInfo() throws Exception
+ {
+ printLockInfoTest(false);
+ }
+
+ /**
+ * Note that this is a bit of a 'white box' test as it checks
+ * the currently coded HTML format. That could change and break
+ * this test; if it does, and there's nothing wrong with the
+ * change, just modify the test.
+ *
+ * @throws Exception
+ */
+ public void testPrintLockInfoAsHtml() throws Exception
+ {
+ printLockInfoTest(true);
+ }
+
+ public void testGetLocalAddress() throws Exception
+ {
+ Configuration c = createConfiguration();
+ c.setCacheMode(CacheMode.REPL_ASYNC);
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(c);
+ wrapper.start();
+ assertTrue("Got an IpAddress", wrapper.getLocalAddress() instanceof IpAddress);
+ }
+
+ public void testGetMembers() throws Exception
+ {
+ Configuration c = createConfiguration();
+ c.setCacheMode(CacheMode.REPL_ASYNC);
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(c);
+ wrapper.start();
+
+ c = createConfiguration();
+ c.setCacheMode(CacheMode.REPL_ASYNC);
+ Cache cache2 = null;
+ try
+ {
+ cache2 = createCache(c);
+ cache2.start();
+ Cache[] caches = new Cache[]{wrapper.getCache(), cache2};
+ TestingUtil.blockUntilViewsReceived(caches, 5000);
+
+ Address addr = wrapper.getLocalAddress();
+ assertNotNull("Got an Address", addr);
+ List members = wrapper.getMembers();
+ assertNotNull("Got members", addr);
+ assertEquals("Got correct number of members", 2, members.size());
+ assertTrue("I am a member", members.contains(addr));
+ }
+ finally
+ {
+ if (cache2 != null)
+ {
+ cache2.destroy();
+ }
+ }
+ }
+
+ public void testDuplicateInvocation() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> cache = registerWrapper();
+ cache.create();
+ cache.start();
+ cache.create();
+ cache.start();
+
+ cache.getCache().put(Fqn.fromString("/a/b/c"), null);
+ assertTrue(cache.getNumberOfNodes() > 0);
+ assertEquals(0, cache.getNumberOfAttributes());
+
+ System.out.println("cache locks before restart:\n" + cache.printLockInfo());
+ cache.destroy();
+ cache.start();
+ System.out.println("cache locks after restart:\n" + cache.printLockInfo());
+
+ assertEquals(0, cache.getNumberOfNodes());
+ assertEquals(0, cache.getNumberOfAttributes());
+
+ cache.stop();
+ cache.destroy();
+ cache.stop();
+ cache.destroy();
+ }
+
+ public void testFailedStart() throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>(createCache(createConfiguration()));
+ registerWrapper(wrapper);
+ assertEquals("Correct state", CacheStatus.INSTANTIATED, wrapper.getCacheStatus());
+ wrapper.create();
+
+ DisruptLifecycleListener listener = new DisruptLifecycleListener();
+ listener.setDisrupt(true);
+ wrapper.getCache().addCacheListener(listener);
+
+ assertEquals("Correct state", CacheStatus.CREATED, wrapper.getCacheStatus());
+ try
+ {
+ wrapper.start();
+ fail("Listener did not prevent start");
+ }
+ catch (CacheException good)
+ {
+ }
+
+ assertEquals("Correct state", CacheStatus.FAILED, wrapper.getCacheStatus());
+
+ listener.setDisrupt(false);
+
+ wrapper.start();
+
+ assertEquals("Correct state", CacheStatus.STARTED, wrapper.getCacheStatus());
+
+ wrapper.getCache().put(Fqn.fromString("/a/b/c"), null);
+ assertTrue(wrapper.getNumberOfNodes() > 0);
+ assertEquals(0, wrapper.getNumberOfAttributes());
+
+ listener.setDisrupt(true);
+ // need to re-add the listener since the failed start would have nullified the notifier.
+ cache.addCacheListener(listener);
+
+ try
+ {
+ wrapper.stop();
+ fail("Listener did not prevent stop");
+ }
+ catch (CacheException good)
+ {
+ }
+
+ assertEquals("Correct state", CacheStatus.FAILED, wrapper.getCacheStatus());
+
+ listener.setDisrupt(false);
+
+ wrapper.stop();
+ assertEquals("Correct state", CacheStatus.STOPPED, wrapper.getCacheStatus());
+ wrapper.destroy();
+ assertEquals("Correct state", CacheStatus.DESTROYED, wrapper.getCacheStatus());
+ }
+
+ private String printCacheDetailsTest(boolean html) throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
+
+ // have to start the cache before we'll have a root
+ cache.start();
+ Fqn fqn = Fqn.fromString("/testing/jmx");
+ cache.put(fqn, "foobar", "barfoo");
+
+ assertEquals("barfoo", cache.get(fqn, "foobar"));
+
+ String details = html ? wrapper.printCacheDetailsAsHtml() : wrapper.printCacheDetails();
+
+
+ System.out.println("Cache details: " + CachePrinter.printCacheDetails(cache));
+ System.out.println("Details: " + details);
+
+ assertTrue("Details include testing", details.contains("testing"));
+ assertTrue("Details include jmx", details.contains("jmx"));
+ assertTrue("Details include foobar", details.contains("foobar"));
+ assertTrue("Details include barfoo", details.contains("barfoo"));
+
+ return details;
+ }
+
+ private String printLockInfoTest(boolean html) throws Exception
+ {
+ Configuration config = createConfiguration();
+ config.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ Cache<String, String> c = createCache(config);
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(c);
+
+// wrapper.setManageCacheLifecycle(true);
+ wrapper.create();
+ wrapper.start();
+
+ TransactionManager tm = config.getRuntimeConfig().getTransactionManager();
+
+ tm.begin();
+ try
+ {
+ Fqn fqn = Fqn.fromString("/testing/jmx");
+ cache.put(fqn, "foobar", "barfoo");
+
+ String locks = html ? wrapper.printLockInfoAsHtml() : wrapper.printLockInfo();
+
+ assertTrue("Details include testing", locks.contains("testing"));
+ assertTrue("Details include jmx", locks.contains("jmx"));
+
+ return locks;
+ }
+ catch (Exception e)
+ {
+ tm.setRollbackOnly();
+ throw e;
+ }
+ finally
+ {
+ tm.commit();
+ }
+
+ }
+
+ private void checkHtml(String html, boolean checkBR)
+ {
+ if (checkBR)
+ assertTrue("Has <br", html.contains("<br"));
+
+ assertTrue("No tabs", html.indexOf('\t') == -1);
+
+ assertTrue("No spaces", html.indexOf(' ') == -1);
+
+ }
+
+ @CacheListener
+ public class DisruptLifecycleListener
+ {
+ private boolean disrupt;
+
+ @CacheStarted
+ public void cacheStarted(Event e)
+ {
+ if (disrupt) throw new IllegalStateException("I don't want to start");
+ }
+
+ @CacheStopped
+ public void cacheStopped(Event e)
+ {
+ if (disrupt) throw new IllegalStateException("I don't want to stop");
+ }
+
+ public void setDisrupt(boolean disrupt)
+ {
+ this.disrupt = disrupt;
+ }
+ }
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTestBase.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTestBase.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTestBase.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,178 @@
+package org.jboss.cache.jmx.deprecated;
+
+import org.jboss.cache.Cache;
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.jmx.CacheJmxWrapperMBean;
+import org.jboss.cache.jmx.JmxRegistrationManager;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import org.jboss.cache.config.Configuration;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertTrue;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.MBeanServerInvocationHandler;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+/**
+ * Tests the JMX wrapper class around the cache.
+ *
+ * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
+ * @author Brian Stansberry
+ */
+@Test(groups = "functional")
+public abstract class CacheJmxWrapperTestBase
+{
+ public static final String CLUSTER_NAME = "CacheMBeanTest";
+
+ protected Cache<String, String> cache;
+ protected CacheJmxWrapperMBean<String, String> jmxWrapper;
+ protected MBeanServer mBeanServer;
+ protected ObjectName mBeanName;
+ protected String mBeanNameStr;
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ mBeanServer = MBeanServerFactory.createMBeanServer("CacheMBeanTest");
+
+ mBeanNameStr = JmxRegistrationManager.CLUSTERED_CACHE_PREFIX + CLUSTER_NAME;
+ mBeanName = new ObjectName(mBeanNameStr);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception
+ {
+ try
+ {
+ cleanup();
+ }
+ finally
+ {
+ if (mBeanServer != null)
+ {
+ MBeanServerFactory.releaseMBeanServer(mBeanServer);
+ mBeanServer = null;
+ }
+ }
+ }
+
+ protected CacheJmxWrapperMBean<String, String> registerWrapper() throws Exception
+ {
+ if (cache == null)
+ cache = createCache(createConfiguration());
+ return registerWrapper(cache);
+ }
+
+ protected CacheJmxWrapperMBean<String, String> registerWrapper(Cache<String, String> toWrap) throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>(toWrap);
+ return registerWrapper(wrapper);
+ }
+
+ protected CacheJmxWrapperMBean<String, String> registerWrapper(Configuration config) throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>();
+ wrapper.setConfiguration(config);
+ return registerWrapper(wrapper);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected CacheJmxWrapperMBean<String, String> registerWrapper(CacheJmxWrapperMBean<String, String> wrapper) throws Exception
+ {
+ ObjectName on = new ObjectName(mBeanNameStr);
+ if (!mBeanServer.isRegistered(on))
+ {
+ mBeanServer.registerMBean(wrapper, on);
+ }
+ jmxWrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
+ return jmxWrapper;
+ }
+
+ protected void unregisterWrapper() throws Exception
+ {
+ mBeanServer.unregisterMBean(mBeanName);
+ }
+
+ protected CacheJmxWrapper<String, String> createWrapper(Configuration config)
+ {
+ CacheJmxWrapper<String, String> wrapper = new CacheJmxWrapper<String, String>();
+ wrapper.setConfiguration(config);
+ return wrapper;
+ }
+
+ protected Cache<String, String> createCache(Configuration config)
+ {
+ CacheFactory<String, String> factory = new DefaultCacheFactory<String, String>();
+ cache = factory.createCache(config, false);
+ return cache;
+ }
+
+ protected Configuration createConfiguration()
+ {
+ Configuration c = new Configuration();
+ c.setClusterName(CLUSTER_NAME);
+ c.setExposeManagementStatistics(true);
+ c.setCacheMode(Configuration.CacheMode.LOCAL);
+ return c;
+ }
+
+ private void cleanup() throws Exception
+ {
+ if (cache != null)
+ {
+ try
+ {
+ cache.stop();
+ }
+ catch (Exception ignored)
+ {
+ }
+
+ cache = null;
+ }
+ if (jmxWrapper != null)
+ {
+ try
+ {
+ jmxWrapper.stop();
+ jmxWrapper.destroy();
+ }
+ catch (Exception ignored)
+ {
+ }
+
+ jmxWrapper = null;
+ }
+
+ if (mBeanServer != null && mBeanName != null && mBeanServer.isRegistered(mBeanName))
+ mBeanServer.unregisterMBean(mBeanName);
+ }
+
+ protected void interceptorRegistrationTest(boolean expectMbeans) throws MalformedObjectNameException, NullPointerException
+ {
+ interceptorRegistrationTest(mBeanNameStr, expectMbeans);
+ }
+
+ protected void interceptorRegistrationTest(String baseName, boolean expectMbeans) throws MalformedObjectNameException, NullPointerException
+ {
+ // should be 3 interceptor MBeans loaded:
+ ObjectName[] interceptorMBeanNames = {
+ new ObjectName(baseName + JmxRegistrationManager.JMX_RESOURCE_KEY + "TxInterceptor"),
+ new ObjectName(baseName + JmxRegistrationManager.JMX_RESOURCE_KEY + "CacheMgmtInterceptor"),
+ };
+
+ for (ObjectName n : interceptorMBeanNames)
+ {
+ if (expectMbeans)
+ assertTrue(n + " should be registered", mBeanServer.isRegistered(n));
+ else
+ assertFalse(n + " should not be registered", mBeanServer.isRegistered(n));
+ }
+ }
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/CacheJmxWrapperTestBase.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,386 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.cache.jmx.deprecated;
+
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.jmx.CacheJmxWrapperMBean;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import static org.testng.AssertJUnit.assertTrue;
+import org.testng.annotations.Test;
+
+/**
+ * Tests the interceptor registration function of CacheJmxWrapper.
+ *
+ * @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
+ * @version $Revision$
+ */
+@Test(groups = "functional")
+public class InterceptorRegistrationTest extends CacheJmxWrapperTestBase
+{
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * cache.start();
+ * wrapper creation and registration.
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans1() throws Exception
+ {
+ // have to start the cache to have any interceptors
+ createCache(createConfiguration());
+ cache.start();
+
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(cache);
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ interceptorRegistrationTest(true);
+
+ // These should be ignored because we
+ // never did wrapper.create()/start()
+ wrapper.stop();
+ wrapper.destroy();
+
+ // Should still be registered
+ interceptorRegistrationTest(true);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * cache.start();
+ * wrapper creation and and start
+ * wrapper registration.
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans2() throws Exception
+ {
+ // have to start the cache to have any interceptors
+ createCache(createConfiguration());
+ cache.start();
+
+ CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>(cache);
+ wrapper.start();
+ wrapper = registerWrapper(wrapper);
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ interceptorRegistrationTest(true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ // Should still no longer be registered
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * Cache not injected
+ * wrapper registered;
+ * wrapper created and started.
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans3() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper(createConfiguration());
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ // have to start the cache to have any interceptors
+ wrapper.create();
+ wrapper.start();
+
+ interceptorRegistrationTest(true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ // Destroy should unregister if we are managing
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * Cache not injected
+ * wrapper created and started.
+ * wrapper registered
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans4() throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
+
+ // have to start the cache to have any interceptors
+ wrapper.create();
+ wrapper.start();
+
+ registerWrapper(wrapper);
+
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ interceptorRegistrationTest(true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ // Destroy should unregister if we are managing
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * cache constructed;
+ * wrapper constructed and registered with manageCacheLifecycle=true
+ * wrapper created and started
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans5() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
+// wrapper.setManageCacheLifecycle(true);
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ // have to start the cache to have any interceptors
+ wrapper.create();
+ wrapper.start();
+
+ interceptorRegistrationTest(true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ // Destroy should unregister if we are managing
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * cache constructed;
+ * wrapper constructed and registered
+ * wrapper created and started
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans6() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = registerWrapper();
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ // have to start the cache to have any interceptors
+ wrapper.create();
+ wrapper.start();
+
+ interceptorRegistrationTest(true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Confirms interceptor mbeans are registered if the following events
+ * occur:
+ * <p/>
+ * cache constructed;
+ * wrapper created and started
+ * wrapper registered
+ *
+ * @throws Exception
+ */
+ public void testInterceptorMBeans7() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>(createCache(createConfiguration()));
+
+ // have to start the cache to have any interceptors
+ wrapper.create();
+ wrapper.start();
+
+ wrapper = registerWrapper(wrapper);
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ interceptorRegistrationTest(true);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Tests that setting registerInterceptors=false disables interceptor
+ * registration when the wrapper is registered before create/start
+ * are called.
+ *
+ * @throws Exception
+ */
+ public void testRegisterInterceptors1() throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
+ wrapper.setRegisterJmxResource(false);
+
+ registerWrapper(wrapper);
+
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ wrapper.create();
+ wrapper.start();
+
+ interceptorRegistrationTest(false);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ /**
+ * Tests that setting registerInterceptors=false disables interceptor
+ * registration when the wrapper is registered after create/start
+ * are called.
+ *
+ * @throws Exception
+ */
+ public void testRegisterInterceptors2() throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
+ wrapper.setRegisterJmxResource(false);
+
+ wrapper.create();
+ wrapper.start();
+
+ registerWrapper(wrapper);
+
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ interceptorRegistrationTest(false);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ public void testExposeManagementStatistics1() throws Exception
+ {
+ Configuration cfg = createConfiguration();
+ cfg.setExposeManagementStatistics(false);
+
+ CacheJmxWrapper<String, String> wrapper = createWrapper(cfg);
+ registerWrapper(cfg);
+
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ wrapper.create();
+ wrapper.start();
+
+ interceptorRegistrationTest(false);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+ }
+
+ public void testExposeManagementStatistics2() throws Exception
+ {
+ Configuration cfg = createConfiguration();
+ cfg.setExposeManagementStatistics(false);
+
+ CacheJmxWrapper<String, String> wrapper = createWrapper(cfg);
+
+ wrapper.create();
+ wrapper.start();
+
+ registerWrapper(wrapper);
+
+ assertTrue("Should be registered", mBeanServer.isRegistered(mBeanName));
+
+ interceptorRegistrationTest(false);
+
+ wrapper.stop();
+ wrapper.destroy();
+
+ interceptorRegistrationTest(false);
+
+ unregisterWrapper();
+
+ interceptorRegistrationTest(false);
+
+ }
+
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/InterceptorRegistrationTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/LegacyConfigurationTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,415 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.cache.jmx.deprecated;
+
+import org.jboss.cache.Version;
+import org.jboss.cache.jmx.CacheJmxWrapperMBean;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import org.jboss.cache.config.BuddyReplicationConfig;
+import org.jboss.cache.config.BuddyReplicationConfig.BuddyLocatorConfig;
+import org.jboss.cache.config.CacheLoaderConfig;
+import org.jboss.cache.config.CacheLoaderConfig.IndividualCacheLoaderConfig;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.Configuration.CacheMode;
+import org.jboss.cache.config.Configuration.NodeLockingScheme;
+import org.jboss.cache.config.EvictionConfig;
+import org.jboss.cache.config.EvictionRegionConfig;
+import org.jboss.cache.config.RuntimeConfig;
+import org.jboss.cache.config.parsing.XmlConfigHelper;
+import org.jboss.cache.eviction.FIFOConfiguration;
+import org.jboss.cache.eviction.FIFOPolicy;
+import org.jboss.cache.eviction.LRUConfiguration;
+import org.jboss.cache.eviction.LRUPolicy;
+import org.jboss.cache.eviction.MRUConfiguration;
+import org.jboss.cache.eviction.MRUPolicy;
+import org.jboss.cache.loader.FileCacheLoader;
+import org.jboss.cache.loader.SingletonStoreCacheLoader;
+import org.jboss.cache.loader.jdbm.JdbmCacheLoader;
+import org.jboss.cache.lock.IsolationLevel;
+import org.jboss.cache.multiplexer.MultiplexerTestHelper;
+import org.jboss.cache.transaction.BatchModeTransactionManagerLookup;
+import org.jgroups.ChannelFactory;
+import org.jgroups.JChannelFactory;
+import org.jgroups.jmx.JChannelFactoryMBean;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.Test;
+import org.w3c.dom.Element;
+
+import javax.management.MBeanServerInvocationHandler;
+import javax.management.ObjectName;
+import javax.transaction.TransactionManager;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.List;
+import java.util.Properties;
+
+/**
+ * Test of the CacheLegacyJmxWrapper.
+ *
+ * @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
+ * @version $Revision$
+ */
+@Test(groups = "functional")
+public class LegacyConfigurationTest extends CacheJmxWrapperTestBase
+{
+ @SuppressWarnings({"deprecation", "unchecked"})
+ public void testLocalCache() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper();
+ registerWrapper(wrapper);
+
+ wrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
+
+ wrapper.setBuddyReplicationConfig(getBuddyReplicationConfig());
+ wrapper.setCacheLoaderConfig(getCacheLoaderConfig());
+ wrapper.setCacheMode("REPL_SYNC");
+ wrapper.setClusterName("LocalTest");
+ wrapper.setClusterConfig(getClusterConfig());
+ wrapper.setEvictionPolicyConfig(getEvictionPolicyConfig());
+ wrapper.setFetchInMemoryState(false);
+ wrapper.setInitialStateRetrievalTimeout(100);
+ wrapper.setInactiveOnStartup(true);
+ wrapper.setNodeLockingScheme("OPTIMISTIC");
+ wrapper.setIsolationLevel("READ_UNCOMMITTED");
+ wrapper.setLockAcquisitionTimeout(200);
+ wrapper.setReplicationVersion("1.0.1");
+ wrapper.setReplQueueInterval(15);
+ wrapper.setReplQueueMaxElements(50);
+ wrapper.setSyncReplTimeout(300);
+ wrapper.setSyncCommitPhase(true);
+ wrapper.setSyncRollbackPhase(true);
+ wrapper.setTransactionManagerLookupClass(BatchModeTransactionManagerLookup.class.getName());
+ wrapper.setExposeManagementStatistics(false);
+ wrapper.setUseRegionBasedMarshalling(true);
+ wrapper.setUseReplQueue(true);
+
+ Configuration c = wrapper.getConfiguration();
+
+ assertEquals("CacheMode", "REPL_SYNC", wrapper.getCacheMode());
+ assertEquals("CacheMode", CacheMode.REPL_SYNC, c.getCacheMode());
+ assertEquals("ClusterName", "LocalTest", wrapper.getClusterName());
+ assertEquals("ClusterName", "LocalTest", c.getClusterName());
+ assertEquals("FetchInMemoryState", false, wrapper.getFetchInMemoryState());
+ assertEquals("FetchInMemoryState", false, c.isFetchInMemoryState());
+ assertEquals("InitialStateRetrievalTimeout", 100, wrapper.getInitialStateRetrievalTimeout());
+ assertEquals("InitialStateRetrievalTimeout", 100, c.getStateRetrievalTimeout());
+ assertEquals("InactiveOnStartup", true, wrapper.isInactiveOnStartup());
+ assertEquals("InactiveOnStartup", true, c.isInactiveOnStartup());
+ assertEquals("NodeLockingScheme", "OPTIMISTIC", wrapper.getNodeLockingScheme());
+ assertEquals("NodeLockingScheme", NodeLockingScheme.OPTIMISTIC, c.getNodeLockingScheme());
+ assertEquals("IsolationLevel", "READ_UNCOMMITTED", wrapper.getIsolationLevel());
+ assertEquals("IsolationLevel", IsolationLevel.READ_UNCOMMITTED, c.getIsolationLevel());
+ assertEquals("LockAcquisitionTimeout", 200, wrapper.getLockAcquisitionTimeout());
+ assertEquals("LockAcquisitionTimeout", 200, c.getLockAcquisitionTimeout());
+ assertEquals("ReplicationVersion", "1.0.1", wrapper.getReplicationVersion());
+ assertEquals("ReplicationVersion", Version.getVersionShort("1.0.1"), c.getReplicationVersion());
+ assertEquals("ReplQueueInterval", 15, wrapper.getReplQueueInterval());
+ assertEquals("ReplQueueInterval", 15, c.getReplQueueInterval());
+ assertEquals("ReplQueueMaxElements", 50, wrapper.getReplQueueMaxElements());
+ assertEquals("ReplQueueMaxElements", 50, c.getReplQueueMaxElements());
+ assertEquals("SyncReplTimeout", 300, wrapper.getSyncReplTimeout());
+ assertEquals("SyncReplTimeout", 300, c.getSyncReplTimeout());
+ assertEquals("SyncCommitPhase", true, wrapper.getSyncCommitPhase());
+ assertEquals("SyncCommitPhase", true, c.isSyncCommitPhase());
+ assertEquals("SyncRollbackPhase", true, wrapper.getSyncRollbackPhase());
+ assertEquals("SyncRollbackPhase", true, c.isSyncRollbackPhase());
+ assertEquals("TransactionManagerLookupClass", BatchModeTransactionManagerLookup.class.getName(), wrapper.getTransactionManagerLookupClass());
+ assertEquals("TransactionManagerLookupClass", BatchModeTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
+ assertEquals("ExposeManagementStatistics", false, wrapper.getExposeManagementStatistics());
+ assertEquals("ExposeManagementStatistics", false, c.getExposeManagementStatistics());
+ assertEquals("UseRegionBasedMarshalling", true, wrapper.getUseRegionBasedMarshalling());
+ assertEquals("UseRegionBasedMarshalling", true, c.isUseRegionBasedMarshalling());
+ assertEquals("UseReplQueue", true, wrapper.getUseReplQueue());
+ assertEquals("UseReplQueue", true, c.isUseReplQueue());
+
+ assertEquals("ClusterConfig", getClusterConfig().toString(), wrapper.getClusterConfig().toString());
+
+ assertEquals("BuddyReplicationConfig", getBuddyReplicationConfig().toString(), wrapper.getBuddyReplicationConfig().toString());
+ BuddyReplicationConfig brc = c.getBuddyReplicationConfig();
+ assertEquals("BR enabled", true, brc.isEnabled());
+ assertEquals("BR auto grav", false, brc.isAutoDataGravitation());
+ assertEquals("BR remove find", false, brc.isDataGravitationRemoveOnFind());
+ assertEquals("BR search backup", false, brc.isDataGravitationSearchBackupTrees());
+ assertEquals("BR comm timeout", 600000, brc.getBuddyCommunicationTimeout());
+ assertEquals("BR poolname", "testpool", brc.getBuddyPoolName());
+ BuddyLocatorConfig blc = brc.getBuddyLocatorConfig();
+ assertEquals("BR locator", "org.jboss.cache.buddyreplication.TestBuddyLocator", blc.getBuddyLocatorClass());
+ Properties props = blc.getBuddyLocatorProperties();
+ assertEquals("BR props", "2", props.get("numBuddies"));
+
+ assertEquals("CacheLoaderConfig", getCacheLoaderConfig().toString(), wrapper.getCacheLoaderConfig().toString());
+ CacheLoaderConfig clc = c.getCacheLoaderConfig();
+ assertEquals("CL passivation", false, clc.isPassivation());
+ assertEquals("CL passivation", true, clc.isShared());
+ assertEquals("CL preload", "/foo", clc.getPreload());
+ List<IndividualCacheLoaderConfig> iclcs = clc.getIndividualCacheLoaderConfigs();
+ IndividualCacheLoaderConfig iclc = iclcs.get(0);
+ assertEquals("CL0 class", FileCacheLoader.class.getName(), iclc.getClassName());
+ assertEquals("CL0 async", false, iclc.isAsync());
+ assertEquals("CL0 fetch", true, iclc.isFetchPersistentState());
+ assertEquals("CL0 ignore", true, iclc.isIgnoreModifications());
+ assertEquals("CL0 purge", true, iclc.isPurgeOnStartup());
+ assertEquals("CL0 singleton", true, iclc.getSingletonStoreConfig().isSingletonStoreEnabled());
+ assertEquals("CL0 singleton class", SingletonStoreCacheLoader.class.getName(), iclc.getSingletonStoreConfig().getSingletonStoreClass());
+ iclc = iclcs.get(1);
+ assertEquals("CL1 class", JdbmCacheLoader.class.getName(), iclc.getClassName());
+ assertEquals("CL1 async", true, iclc.isAsync());
+ assertEquals("CL1 fetch", false, iclc.isFetchPersistentState());
+ assertEquals("CL1 ignore", false, iclc.isIgnoreModifications());
+ assertEquals("CL1 purge", false, iclc.isPurgeOnStartup());
+ assertEquals("CL1 singleton", false, iclc.getSingletonStoreConfig().isSingletonStoreEnabled());
+ assertEquals("CL1 singleton class", SingletonStoreCacheLoader.class.getName(), iclc.getSingletonStoreConfig().getSingletonStoreClass());
+
+ assertEquals("EvictionPolicyConfig", getEvictionPolicyConfig().toString(), wrapper.getEvictionPolicyConfig().toString());
+ EvictionConfig ec = c.getEvictionConfig();
+ assertEquals("EC queue size", 20000, ec.getDefaultEventQueueSize());
+ assertEquals("EC wakeup", 5000, ec.getWakeupInterval());
+ assertEquals("EC default pol", LRUPolicy.class.getName(), ec.getDefaultEvictionPolicyClass());
+ List<EvictionRegionConfig> ercs = ec.getEvictionRegionConfigs();
+ EvictionRegionConfig erc = ercs.get(0);
+ assertEquals("ERC0 name", "/_default_", erc.getRegionName());
+ assertEquals("ERC0 queue size", 1000, erc.getEventQueueSize());
+ LRUConfiguration lru = (LRUConfiguration) erc.getEvictionPolicyConfig();
+ assertEquals("EPC0 pol", LRUPolicy.class.getName(), lru.getEvictionPolicyClass());
+ assertEquals("EPC0 maxnodes", 5000, lru.getMaxNodes());
+ assertEquals("EPC0 ttl", 1000000, lru.getTimeToLive());
+ erc = ercs.get(1);
+ assertEquals("ERC1 name", "/org/jboss/data", erc.getRegionName());
+ assertEquals("ERC1 queue size", 20000, erc.getEventQueueSize());
+ FIFOConfiguration fifo = (FIFOConfiguration) erc.getEvictionPolicyConfig();
+ assertEquals("EPC1 pol", FIFOPolicy.class.getName(), fifo.getEvictionPolicyClass());
+ assertEquals("EPC1 maxnodes", 5000, fifo.getMaxNodes());
+ erc = ercs.get(2);
+ assertEquals("ERC2 name", "/test", erc.getRegionName());
+ assertEquals("ERC2 queue size", 20000, erc.getEventQueueSize());
+ MRUConfiguration mru = (MRUConfiguration) erc.getEvictionPolicyConfig();
+ assertEquals("EPC2 pol", MRUPolicy.class.getName(), mru.getEvictionPolicyClass());
+ assertEquals("EPC2 maxnodes", 10000, mru.getMaxNodes());
+ erc = ercs.get(3);
+ assertEquals("ERC3 name", "/maxAgeTest", erc.getRegionName());
+ assertEquals("ERC3 queue size", 20000, erc.getEventQueueSize());
+ lru = (LRUConfiguration) erc.getEvictionPolicyConfig();
+ assertEquals("EPC3 pol", LRUPolicy.class.getName(), lru.getEvictionPolicyClass());
+ assertEquals("EPC3 maxnodes", 10000, lru.getMaxNodes());
+ assertEquals("EPC3 maxage", 10000, lru.getMaxAge());
+ assertEquals("EPC3 ttl", 8000, lru.getTimeToLive());
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testRuntimeConfig() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>();
+ registerWrapper(wrapper);
+
+ wrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
+
+ // Fake a TM by making a bogus proxy
+ TransactionManager tm = (TransactionManager) Proxy.newProxyInstance(getClass().getClassLoader(),
+ new Class[]{TransactionManager.class}, new MockInvocationHandler());
+ wrapper.setTransactionManager(tm);
+ ChannelFactory cf = new JChannelFactory();
+ wrapper.setMuxChannelFactory(cf);
+
+ RuntimeConfig rc = wrapper.getConfiguration().getRuntimeConfig();
+
+ assertSame("Same TM", tm, wrapper.getTransactionManager());
+ assertSame("Same TM", tm, rc.getTransactionManager());
+ assertSame("Same ChannelFactory", cf, wrapper.getMuxChannelFactory());
+ assertSame("Same ChannelFactory", cf, rc.getMuxChannelFactory());
+ }
+
+ @SuppressWarnings("unchecked")
+ public void testLegacyMuxChannelCreation() throws Exception
+ {
+ CacheJmxWrapperMBean<String, String> wrapper = new CacheJmxWrapper<String, String>();
+ registerWrapper(wrapper);
+
+ wrapper = (CacheJmxWrapperMBean<String, String>) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, mBeanName, CacheJmxWrapperMBean.class, false);
+ wrapper.setMultiplexerStack(MultiplexerTestHelper.MUX_STACK);
+
+ JChannelFactory factory = new JChannelFactory();
+ factory.setDomain("jbc.mux.test");
+ factory.setExposeChannels(false);
+ factory.setMultiplexerConfig(MultiplexerTestHelper.getClusterConfigElement(getDefaultProperties()));
+
+ ObjectName on = new ObjectName("jgroups:service=Mux");
+ mBeanServer.registerMBean(new org.jgroups.jmx.JChannelFactory(factory), on);
+
+ wrapper.setMultiplexerService((JChannelFactoryMBean) MBeanServerInvocationHandler.newProxyInstance(mBeanServer, on, JChannelFactoryMBean.class, false));
+
+ wrapper.start();
+
+ RuntimeConfig rc = wrapper.getConfiguration().getRuntimeConfig();
+ assertNotNull("Channel created", rc.getChannel());
+ }
+
+ protected static Element getBuddyReplicationConfig() throws Exception
+ {
+
+ String xmlStr =
+ " <buddy enabled=\"true\" poolName=\"testpool\" communicationTimeout=\"600000\">\n" +
+ " <dataGravitation auto=\"false\" removeOnFind=\"false\" searchBackupTrees=\"false\"/>\n" +
+ " <locator class=\"org.jboss.cache.buddyreplication.TestBuddyLocator\">\n" +
+ " <properties>\n" +
+ " numBuddies = 2\n" +
+ " </properties>\n" +
+ " </locator>\n" +
+ " </buddy>";
+ return XmlConfigHelper.stringToElement(xmlStr);
+ }
+
+ protected static Element getCacheLoaderConfig() throws Exception
+ {
+ String xmlStr =
+ " <loaders passivation=\"false\" shared=\"true\">\n" +
+ " <preload>\n" +
+ " <node fqn=\"/foo\"/>\n" +
+ " </preload>\n" +
+ " <loader class=\"org.jboss.cache.loader.FileCacheLoader\" async=\"false\" fetchPersistentState=\"true\"\n" +
+ " ignoreModifications=\"true\" purgeOnStartup=\"true\">\n" +
+ " <properties>\n" +
+ " location=/tmp\n " +
+ " </properties>\n" +
+ " <singletonStore enabled=\"true\" /> \n" +
+ " </loader>\n" +
+ " <loader class=\"org.jboss.cache.loader.jdbm.JdbmCacheLoader\" async=\"true\" fetchPersistentState=\"false\"\n" +
+ " ignoreModifications=\"false\" purgeOnStartup=\"false\">\n" +
+ " <properties>\n" +
+ " location=/home/bstansberry\n" +
+ " </properties>\n" +
+ " <singletonStore enabled=\"false\" /> \n" +
+ " </loader>\n" +
+ " </loaders>";
+ return XmlConfigHelper.stringToElement(xmlStr);
+ }
+
+ protected static Element getEvictionPolicyConfig() throws Exception
+ {
+
+ String xmlStr =
+ " <eviction wakeUpInterval=\"5000\" defaultPolicyClass=\"org.jboss.cache.eviction.LRUPolicy\" defaultEventQueueSize=\"20000\">\n" +
+ " <default eventQueueSize=\"1000\">\n" +
+ " <attribute name=\"maxNodes\">5000</attribute>\n" +
+ " <attribute name=\"timeToLive\">1000000</attribute>\n" +
+ " </default>\n" +
+ "<region name=\"/org/jboss/data\" policyClass=\"org.jboss.cache.eviction.FIFOPolicy\">\n" +
+ " <attribute name=\"maxNodes\">5000</attribute>\n" +
+ "</region>\n" +
+ "<region name=\"/test/\" policyClass=\"org.jboss.cache.eviction.MRUPolicy\">\n" +
+ " <attribute name=\"maxNodes\">10000</attribute>\n" +
+ "</region>\n" +
+ "<region name=\"/maxAgeTest/\">\n" +
+ " <attribute name=\"maxNodes\">10000</attribute>\n" +
+ " <attribute name=\"timeToLiveSeconds\">8</attribute>\n" +
+ " <attribute name=\"maxAgeSeconds\">10</attribute>\n" +
+ "</region>\n" +
+ " </eviction>";
+ return XmlConfigHelper.stringToElement(xmlStr);
+ }
+
+ protected static Element getClusterConfig() throws Exception
+ {
+ String xml =
+ "<jgroupsConfig>\n" +
+ "<UDP mcast_addr=\"228.10.10.10\"\n" +
+ " mcast_port=\"45588\"\n" +
+ " tos=\"8\"\n" +
+ " ucast_recv_buf_size=\"20000000\"\n" +
+ " ucast_send_buf_size=\"640000\"\n" +
+ " mcast_recv_buf_size=\"25000000\"\n" +
+ " mcast_send_buf_size=\"640000\"\n" +
+ " loopback=\"false\"\n" +
+ " discard_incompatible_packets=\"true\"\n" +
+ " max_bundle_size=\"64000\"\n" +
+ " max_bundle_timeout=\"30\"\n" +
+ " use_incoming_packet_handler=\"true\"\n" +
+ " ip_ttl=\"2\"\n" +
+ " enable_bundling=\"false\"\n" +
+ " enable_diagnostics=\"true\"\n" +
+ " use_concurrent_stack=\"true\"\n" +
+ " thread_naming_pattern=\"pl\"\n" +
+ " thread_pool.enabled=\"true\"\n" +
+ " thread_pool.min_threads=\"1\"\n" +
+ " thread_pool.max_threads=\"25\"\n" +
+ " thread_pool.keep_alive_time=\"30000\"\n" +
+ " thread_pool.queue_enabled=\"true\"\n" +
+ " thread_pool.queue_max_size=\"10\"\n" +
+ " thread_pool.rejection_policy=\"Run\"\n" +
+ " oob_thread_pool.enabled=\"true\"\n" +
+ " oob_thread_pool.min_threads=\"1\"\n" +
+ " oob_thread_pool.max_threads=\"4\"\n" +
+ " oob_thread_pool.keep_alive_time=\"10000\"\n" +
+ " oob_thread_pool.queue_enabled=\"true\"\n" +
+ " oob_thread_pool.queue_max_size=\"10\"\n" +
+ " oob_thread_pool.rejection_policy=\"Run\"/>\n" +
+ " <PING timeout=\"2000\" num_initial_members=\"3\"/>\n" +
+ " <MERGE2 max_interval=\"30000\" min_interval=\"10000\"/>\n" +
+ " <FD_SOCK/>\n" +
+ " <FD timeout=\"10000\" max_tries=\"5\" shun=\"true\"/>\n" +
+ " <VERIFY_SUSPECT timeout=\"1500\"/>\n" +
+ " <pbcast.NAKACK max_xmit_size=\"60000\"\n" +
+ " use_mcast_xmit=\"false\" gc_lag=\"0\"\n" +
+ " retransmit_timeout=\"300,600,1200,2400,4800\"\n" +
+ " discard_delivered_msgs=\"true\"/>\n" +
+ " <UNICAST timeout=\"300,600,1200,2400,3600\"/>\n" +
+ " <pbcast.STABLE stability_delay=\"1000\" desired_avg_gossip=\"50000\"\n" +
+ " max_bytes=\"400000\"/>\n" +
+ " <pbcast.GMS print_local_addr=\"true\" join_timeout=\"5000\"\n" +
+ " join_retry_timeout=\"2000\" shun=\"false\"\n" +
+ " view_bundling=\"true\" view_ack_collection_timeout=\"5000\"/>\n" +
+ " <FRAG2 frag_size=\"60000\"/>\n" +
+ " <pbcast.STREAMING_STATE_TRANSFER use_reading_thread=\"true\"/>\n" +
+ " <pbcast.FLUSH timeout=\"0\"/>\n" +
+ "</jgroupsConfig>";
+ return XmlConfigHelper.stringToElement(xml);
+ }
+
+ protected String getDefaultProperties()
+ {
+ return "UDP(mcast_addr=224.0.0.36;mcast_port=55566;ip_ttl=32;" +
+ "mcast_send_buf_size=150000;mcast_recv_buf_size=80000):" +
+ "PING(timeout=1000;num_initial_members=2):" +
+ "MERGE2(min_interval=5000;max_interval=10000):" +
+ "FD_SOCK:" +
+ "VERIFY_SUSPECT(timeout=1500):" +
+ "pbcast.NAKACK(gc_lag=50;max_xmit_size=8192;retransmit_timeout=600,1200,2400,4800):" +
+ "UNICAST(timeout=600,1200,2400,4800):" +
+ "pbcast.STABLE(desired_avg_gossip=20000):" +
+ "FRAG(frag_size=8192;down_thread=false;up_thread=false):" +
+ "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" +
+ "shun=false;print_local_addr=true):" +
+ "pbcast.STATE_TRANSFER";
+ }
+
+ class MockInvocationHandler implements InvocationHandler
+ {
+
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
+ {
+ return null;
+ }
+
+ }
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LegacyConfigurationTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/LifecycleNotificationTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,105 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2006, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.cache.jmx.deprecated;
+
+import static org.testng.AssertJUnit.assertEquals;
+import org.testng.AssertJUnit;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import org.jboss.cache.jmx.CacheJmxWrapperMBean;
+
+import javax.management.AttributeChangeNotification;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * A LifecycleNotificationTest.
+ *
+ * @author <a href="brian.stansberry(a)jboss.com">Brian Stansberry</a>
+ * @version $Revision$
+ */
+public class LifecycleNotificationTest extends CacheJmxWrapperTestBase
+{
+ public void testGetStateAndStateNotification() throws Exception
+ {
+ CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
+ StateNotificationListener listener = new StateNotificationListener();
+ wrapper.addNotificationListener(listener, null, null);
+
+ AssertJUnit.assertEquals("Correct state after instanitation",
+ CacheJmxWrapperMBean.UNREGISTERED, wrapper.getState());
+
+ registerWrapper(wrapper);
+ assertEquals("Correct state after registration",
+ CacheJmxWrapperMBean.REGISTERED, wrapper.getState());
+
+ wrapper.create();
+ assertEquals("Correct state after create",
+ CacheJmxWrapperMBean.CREATED, wrapper.getState());
+
+ wrapper.start();
+ assertEquals("Correct state after start",
+ CacheJmxWrapperMBean.STARTED, wrapper.getState());
+
+ wrapper.stop();
+ assertEquals("Correct state after stop",
+ CacheJmxWrapperMBean.STOPPED, wrapper.getState());
+
+ wrapper.destroy();
+ assertEquals("Correct state after destroy",
+ CacheJmxWrapperMBean.DESTROYED, wrapper.getState());
+
+ unregisterWrapper();
+ assertEquals("Correct state after unregistration",
+ CacheJmxWrapperMBean.UNREGISTERED, wrapper.getState());
+
+ System.out.println(listener.notifications);
+ assertEquals("Correct number of notifications received", 4, listener.notifications.size());
+ assertEquals("Correct first notification", new Integer(CacheJmxWrapperMBean.STARTING), listener.notifications.get(0));
+ assertEquals("Correct second notification", new Integer(CacheJmxWrapperMBean.STARTED), listener.notifications.get(1));
+ assertEquals("Correct third notification", new Integer(CacheJmxWrapperMBean.STOPPING), listener.notifications.get(2));
+ assertEquals("Correct fourth notification", new Integer(CacheJmxWrapperMBean.STOPPED), listener.notifications.get(3));
+ }
+
+ private static class StateNotificationListener
+ implements NotificationListener
+ {
+ private List<Integer> notifications = new LinkedList<Integer>();
+
+ public void handleNotification(Notification msg, Object handback)
+ {
+ if (msg instanceof AttributeChangeNotification)
+ {
+ AttributeChangeNotification change = (AttributeChangeNotification) msg;
+ String attrName = change.getAttributeName();
+ Object newValue = change.getNewValue();
+ if ("State".equals(attrName) && newValue != null && newValue instanceof Integer)
+ {
+ notifications.add((Integer) newValue);
+ }
+ }
+ }
+ }
+
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/LifecycleNotificationTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/NotificationTest.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/NotificationTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/NotificationTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/NotificationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,470 @@
+package org.jboss.cache.jmx.deprecated;
+
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.CacheSPI;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.Fqn;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import org.jboss.cache.jmx.JmxRegistrationManager;
+import org.jboss.cache.jmx.CacheNotificationBroadcaster;
+import org.jboss.cache.config.CacheLoaderConfig;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.Configuration.CacheMode;
+import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
+import org.jboss.cache.loader.CacheLoader;
+import static org.testng.AssertJUnit.*;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+import javax.management.Notification;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import java.util.EnumSet;
+import java.util.HashMap;
+
+/**
+ * Functional tests for CacheJmxWrapper broadcast of cache event notifications
+ *
+ * @author Jerry Gauthier
+ * @version $Id$
+ */
+@Test(groups = {"functional"})
+public class NotificationTest
+{
+ protected static final String CLUSTER_NAME = "NotificationTestCluster";
+
+ protected static final String CAPITAL = "capital";
+ protected static final String CURRENCY = "currency";
+ protected static final String POPULATION = "population";
+ protected static final String EUROPE_NODE = "Europe";
+
+ public enum Type
+ {
+ STARTED, STOPPED, PRECREATE, POSTCREATE, PREEVICT, POSTEVICT,
+ PRELOAD, POSTLOAD, PREREMOVE, POSTREMOVE, PREVISIT, POSTVISIT,
+ PREMODIFY, POSTMODIFY, PREACTIVATE, POSTACTIVATE, PREPASSIVATE,
+ POSTPASSIVATE, VIEWCHANGE
+ }
+
+ protected MBeanServer m_server;
+ protected EnumSet<Type> events = EnumSet.noneOf(Type.class);
+
+ protected CacheSPI<Object, Object> cache = null;
+ protected boolean optimistic = false;
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ m_server = MBeanServerFactory.createMBeanServer();
+
+ Object cacheMBean = createCacheAndJmxWrapper();
+
+ // bind manually for now.
+ ObjectName mgmt = getWrapperObjectName();
+
+ m_server.registerMBean(cacheMBean, mgmt);
+ }
+
+ protected Object createCacheAndJmxWrapper() throws Exception
+ {
+ cache = createCache(CLUSTER_NAME);
+ return new CacheJmxWrapper<Object, Object>(cache);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception
+ {
+ try
+ {
+ cleanup();
+ }
+ finally
+ {
+ // make sure we stop the mbean server
+ if (m_server != null)
+ MBeanServerFactory.releaseMBeanServer(m_server);
+ }
+ }
+
+ protected void cleanup() throws Exception
+ {
+ events.clear();
+
+ destroyCache();
+
+ if (m_server != null)
+ {
+ ObjectName mgmt = getWrapperObjectName();
+ if (m_server.isRegistered(mgmt))
+ m_server.unregisterMBean(mgmt);
+ }
+ }
+
+ protected void destroyCache()
+ {
+ if (cache != null)
+ {
+ // stop the cache before the listener is unregistered
+ //cache1.stop();
+ cache.destroy();
+ cache = null;
+ }
+ }
+
+ protected ObjectName getWrapperObjectName() throws Exception
+ {
+ return new ObjectName(JmxRegistrationManager.CLUSTERED_CACHE_PREFIX + CLUSTER_NAME);
+ }
+
+ public void testNotifications() throws Exception
+ {
+ assertNotNull("MBeanServer is null.", m_server);
+ assertNotNull("Cache is null.", cache);
+
+ ObjectName mgmt = getWrapperObjectName();
+ MyListener listener = new MyListener(mgmt);
+
+
+ m_server.addNotificationListener(mgmt, listener, null, null);
+
+ // start the cache after registering listener - this will trigger CacheStarted
+ // since cache is defined with cluster, thiswill also trigger ViewChange
+ cache.start();
+
+ // add a node - this will trigger NodeCreated, NodeModify(pre/post) and NodeModified
+ HashMap<Object, Object> albania = new HashMap<Object, Object>(4);
+ albania.put(CAPITAL, "Tirana");
+ albania.put(CURRENCY, "Lek");
+ cache.put("Europe/Albania", albania);
+
+ // modify a node - this will trigger NodeModified and NodeModify(pre/post)
+ cache.put("Europe/Albania", POPULATION, 3563112);
+
+ // retrieve an attribute - this will trigger NodeVisited
+ Fqn key = Fqn.fromString("Europe/Albania");
+ assertNotNull("Retrieval error: expected to retrieve " + CURRENCY + " for " + key, cache.get(key, CURRENCY));
+
+ // evict the node - this will trigger NodePassivate, NodeEvicted and NodeEvict(pre/post)
+ cache.evict(key);
+
+ // retrieve the attribute again - this will trigger NodeVisited and NodeActivate
+ assertNotNull("Retrieval error: expected to retrieve " + CURRENCY + " for " + key, cache.get(key, CURRENCY));
+
+ // remove the node - this will trigger NodeRemoved and NodeRemove(pre/post)
+ cache.removeNode(key);
+
+ // clean up before stopping the cache
+ CacheLoader cl = cache.getCacheLoaderManager().getCacheLoader();
+ cl.remove(Fqn.fromString(EUROPE_NODE));
+
+ // stop the cache
+ cache.stop();
+ m_server.removeNotificationListener(mgmt, listener);
+
+ // run the tests
+ assertTrue("Expected CacheStarted notification", events.contains(Type.STARTED));
+ assertTrue("Expected CacheStopped notification", events.contains(Type.STOPPED));
+ assertTrue("Expected NodeCreated notification", events.contains(Type.PRECREATE));
+ assertTrue("Expected NodeCreated notification", events.contains(Type.POSTCREATE));
+ assertTrue("Expected NodeEvicted notification", events.contains(Type.PREEVICT));
+ assertTrue("Expected NodeEvicted notification", events.contains(Type.POSTEVICT));
+ assertTrue("Expected NodeLoaded notification", events.contains(Type.PRELOAD));
+ assertTrue("Expected NodeLoaded notification", events.contains(Type.POSTLOAD));
+ assertTrue("Expected NodeVisited notification", events.contains(Type.PREVISIT));
+ assertTrue("Expected NodeVisited notification", events.contains(Type.POSTVISIT));
+ assertTrue("Expected NodeActivated notification", events.contains(Type.PREACTIVATE));
+ assertTrue("Expected NodeActivated notification", events.contains(Type.POSTACTIVATE));
+ assertTrue("Expected NodeModified notification", events.contains(Type.PREMODIFY));
+ assertTrue("Expected NodeModified notification", events.contains(Type.POSTMODIFY));
+ assertTrue("Expected NodePassivated notification", events.contains(Type.PREPASSIVATE));
+ assertTrue("Expected NodePassivated notification", events.contains(Type.POSTPASSIVATE));
+ assertTrue("Expected NodeRemoved notification", events.contains(Type.PREREMOVE));
+ assertTrue("Expected NodeRemoved notification", events.contains(Type.POSTREMOVE));
+ assertTrue("Expected ViewChange notification", events.contains(Type.VIEWCHANGE));
+ validateHealthyListener(listener);
+ }
+
+ public void testEarlyRegistration() throws Exception
+ {
+ // undo setup
+ cleanup();
+
+ CacheJmxWrapper<Object, Object> wrapper = new CacheJmxWrapper<Object, Object>();
+ ObjectName mgmt = getWrapperObjectName();
+ m_server.registerMBean(wrapper, mgmt);
+ MyListener listener = new MyListener(mgmt);
+ m_server.addNotificationListener(mgmt, listener, null, null);
+
+ cache = createCache(CLUSTER_NAME);
+ wrapper.setCache(cache);
+ cache.start();
+ try
+ {
+ assertTrue("Expected CacheStarted notification", events.contains(Type.STARTED));
+ validateHealthyListener(listener);
+ }
+ finally
+ {
+ cache.stop();
+ }
+ }
+
+ public void testLateRegistration() throws Exception
+ {
+ assertNotNull("MBeanServer is null.", m_server);
+ assertNotNull("Cache is null.", cache);
+
+ // start the cache before registering listener
+ cache.start();
+
+ try
+ {
+ ObjectName mgmt = getWrapperObjectName();
+ MyListener listener = new MyListener(mgmt);
+
+ m_server.addNotificationListener(mgmt, listener, null, null);
+
+ // add a node - this will trigger NodeCreated, NodeModify(pre/post) and NodeModified
+ HashMap<Object, Object> albania = new HashMap<Object, Object>(4);
+ albania.put(CAPITAL, "Tirana");
+ albania.put(CURRENCY, "Lek");
+ cache.put("Europe/Albania", albania);
+
+ // run the tests
+ assertTrue("Expected NodeModified notification", events.contains(Type.PREMODIFY));
+ assertTrue("Expected NodeModified notification", events.contains(Type.POSTMODIFY));
+ validateHealthyListener(listener);
+ }
+ finally
+ {
+ cache.stop();
+ }
+ }
+
+ public void testListenerRemoval() throws Exception
+ {
+ assertNotNull("MBeanServer is null.", m_server);
+ assertNotNull("Cache is null.", cache);
+
+ ObjectName mgmt = getWrapperObjectName();
+ MyListener listener = new MyListener(mgmt);
+
+ m_server.addNotificationListener(mgmt, listener, null, null);
+
+ // start the cache after registering listener - this will trigger CacheStarted
+ // since cache is defined with cluster, thiswill also trigger ViewChange
+ cache.start();
+ boolean ok = false;
+ try
+ {
+ assertTrue("Expected CacheStarted notification", events.contains(Type.STARTED));
+
+ m_server.removeNotificationListener(mgmt, listener);
+ ok = true;
+ }
+ finally
+ {
+ cache.stop();
+ if (ok)
+ {
+ assertFalse("Expected no CacheStopped notification", events.contains(Type.STOPPED));
+ validateHealthyListener(listener);
+ }
+ }
+ }
+
+ private CacheSPI<Object, Object> createCache(String clusterName) throws Exception
+ {
+ Configuration config = createConfiguration(clusterName);
+ CacheFactory<Object, Object> factory = new DefaultCacheFactory<Object, Object>();
+ CacheSPI<Object, Object> cache = (CacheSPI<Object, Object>) factory.createCache(config, false);
+
+ cache.create();
+ // start the cache after the listener has been registered
+ //cache.start();
+ return cache;
+ }
+
+ protected Configuration createConfiguration(String clusterName) throws Exception
+ {
+ Configuration config = UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.REPL_SYNC);
+ config.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ config.setCacheLoaderConfig(getCacheLoaderConfig("location=" + getTempDir()));
+ config.setExposeManagementStatistics(true);
+ config.setClusterName(clusterName);
+ if (optimistic)
+ {
+ config.setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
+ config.setNodeLockingScheme("OPTIMISTIC");
+ }
+
+ return config;
+ }
+
+ private static String getTempDir()
+ {
+ return System.getProperty("java.io.tempdir", "/tmp");
+ }
+
+ private static boolean getPre(Object data)
+ {
+ assertNotNull("User data is null, should be Object[]", data);
+ assertTrue("User data is " + data.getClass().getName() + ", should be Object[]", data instanceof Object[]);
+
+ Object[] parms = (Object[]) data;
+ assertTrue("Parameter is " + parms[1].getClass().getName() + ", should be Boolean", parms[1] instanceof Boolean);
+ return (Boolean) parms[1];
+ }
+
+ protected static CacheLoaderConfig getCacheLoaderConfig(String properties) throws Exception
+ {
+ return UnitTestCacheConfigurationFactory.buildSingleCacheLoaderConfig(true, "",
+ "org.jboss.cache.loader.FileCacheLoader", properties, false, false, true, false, false);
+ }
+
+ private static void validateHealthyListener(MyListener listener)
+ {
+ if (listener.failure != null)
+ throw listener.failure;
+ if (listener.exception != null)
+ throw listener.exception;
+ }
+
+ private class MyListener implements NotificationListener
+ {
+ private RuntimeException exception;
+ private AssertionError failure;
+ private final String emitterObjectName;
+
+ MyListener(ObjectName emitter)
+ {
+ this.emitterObjectName = emitter.getCanonicalName();
+ }
+
+ public void handleNotification(Notification notification, Object handback)
+ {
+ try
+ {
+ String type = notification.getType();
+ Object userData = notification.getUserData();
+
+ if (type.equals(CacheNotificationBroadcaster.NOTIF_CACHE_STARTED))
+ {
+ events.add(Type.STARTED);
+ assertEquals("Correct object name in start notification", emitterObjectName, userData);
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_CACHE_STOPPED))
+ {
+ events.add(Type.STOPPED);
+ assertEquals("Correct object name in stop notification", emitterObjectName, userData);
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_CREATED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PRECREATE);
+ }
+ else
+ {
+ events.add(Type.POSTCREATE);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_EVICTED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PREEVICT);
+ }
+ else
+ {
+ events.add(Type.POSTEVICT);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_LOADED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PRELOAD);
+ }
+ else
+ {
+ events.add(Type.POSTLOAD);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_REMOVED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PREREMOVE);
+ }
+ else
+ {
+ events.add(Type.POSTREMOVE);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_VISITED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PREVISIT);
+ }
+ else
+ {
+ events.add(Type.POSTVISIT);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_VIEW_CHANGED))
+ {
+ events.add(Type.VIEWCHANGE);
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_ACTIVATED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PREACTIVATE);
+ }
+ else
+ {
+ events.add(Type.POSTACTIVATE);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_MODIFIED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PREMODIFY);
+ }
+ else
+ {
+ events.add(Type.POSTMODIFY);
+ }
+ }
+ else if (type.equals(CacheNotificationBroadcaster.NOTIF_NODE_PASSIVATED))
+ {
+ if (getPre(userData))
+ {
+ events.add(Type.PREPASSIVATE);
+ }
+ else
+ {
+ events.add(Type.POSTPASSIVATE);
+ }
+ }
+ }
+ catch (RuntimeException e)
+ {
+ // Store so the test can rethrow
+ exception = e;
+ }
+ catch (AssertionError e)
+ {
+ // Store so the test can rethrow
+ failure = e;
+ }
+ }
+ }
+
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/NotificationTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java (from rev 6541, core/trunk/src/test/java/org/jboss/cache/jmx/OptimisticNotificationTest.java)
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java 2008-08-08 17:00:29 UTC (rev 6546)
@@ -0,0 +1,19 @@
+/*
+ * JBoss, Home of Professional Open Source
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+package org.jboss.cache.jmx.deprecated;
+
+
+/**
+ * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
+ */
+public class OptimisticNotificationTest extends NotificationTest
+{
+ public OptimisticNotificationTest()
+ {
+ optimistic = true;
+ }
+}
Property changes on: core/trunk/src/test/java/org/jboss/cache/jmx/deprecated/OptimisticNotificationTest.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
16 years, 5 months
JBoss Cache SVN: r6544 - in core/trunk/src/main/java/org/jboss/cache: interceptors/base and 1 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-08-08 05:37:39 -0400 (Fri, 08 Aug 2008)
New Revision: 6544
Added:
core/trunk/src/main/java/org/jboss/cache/jmx/JmxStatisticsExposer.java
Removed:
core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java
Modified:
core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java
core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
Log:
added management stats for replication
Modified: core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-08-07 19:23:46 UTC (rev 6543)
+++ core/trunk/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-08-08 09:37:39 UTC (rev 6544)
@@ -32,6 +32,8 @@
import org.jboss.cache.transaction.TransactionTable;
import org.jboss.cache.util.ThreadGate;
import org.jboss.cache.util.reflect.ReflectionUtil;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
import org.jgroups.Address;
import org.jgroups.Channel;
import org.jgroups.ChannelException;
@@ -53,6 +55,7 @@
import java.util.List;
import java.util.Set;
import java.util.Vector;
+import java.text.NumberFormat;
/**
* Manager that handles all RPC calls between JBoss Cache instances
@@ -64,6 +67,9 @@
private Channel channel;
private final Log log = LogFactory.getLog(RPCManagerImpl.class);
private List<Address> members;
+ private long replicationCount;
+ private long replicationFailures;
+ private boolean statisticsEnabled;
private final Object coordinatorLock = new Object();
/**
@@ -407,65 +413,65 @@
public List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand command, int mode, long timeout, RspFilter responseFilter, boolean useOutOfBandMessage) throws Exception
{
- // short circuit if we don't have an RpcDispatcher!
- if (rpcDispatcher == null) return null;
-
- int modeToUse = mode;
- int preferredMode;
- if ((preferredMode = spi.getInvocationContext().getOptionOverrides().getGroupRequestMode()) > -1)
- modeToUse = preferredMode;
-
- if (trace)
- log.trace("callRemoteMethods(): valid members are " + recipients + " methods: " + command + " Using OOB? " + useOutOfBandMessage);
-
- if (channel.flushSupported())
- {
- if (!flushBlockGate.await(configuration.getStateRetrievalTimeout()))
- throw new TimeoutException("State retrieval timed out waiting for flush unblock.");
- }
-
- useOutOfBandMessage = false;
-
- RspList rsps = rpcDispatcher.invokeRemoteCommands(recipients, command, modeToUse, timeout, isUsingBuddyReplication, useOutOfBandMessage, responseFilter);
-
- if (mode == GroupRequest.GET_NONE) return Collections.emptyList();// async case
-
- if (trace)
- log.trace("(" + getLocalAddress() + "): responses for method " + command.getClass().getSimpleName() + ":\n" + rsps);
-
- // short-circuit no-return-value calls.
- if (rsps == null) return Collections.emptyList();
-
- List<Object> retval = new ArrayList<Object>(rsps.size());
-
- for (Rsp rsp : rsps.values())
- {
- if (rsp.wasSuspected() || !rsp.wasReceived())
+ boolean success = true;
+ try {
+ // short circuit if we don't have an RpcDispatcher!
+ if (rpcDispatcher == null) return null;
+ int modeToUse = mode;
+ int preferredMode;
+ if ((preferredMode = spi.getInvocationContext().getOptionOverrides().getGroupRequestMode()) > -1)
+ modeToUse = preferredMode;
+ if (trace)
+ log.trace("callRemoteMethods(): valid members are " + recipients + " methods: " + command + " Using OOB? " + useOutOfBandMessage);
+ if (channel.flushSupported())
{
- CacheException ex;
- if (rsp.wasSuspected())
+ if (!flushBlockGate.await(configuration.getStateRetrievalTimeout()))
+ throw new TimeoutException("State retrieval timed out waiting for flush unblock.");
+ }
+ useOutOfBandMessage = false;
+ RspList rsps = rpcDispatcher.invokeRemoteCommands(recipients, command, modeToUse, timeout, isUsingBuddyReplication, useOutOfBandMessage, responseFilter);
+ if (mode == GroupRequest.GET_NONE) return Collections.emptyList();// async case
+ if (trace)
+ log.trace("(" + getLocalAddress() + "): responses for method " + command.getClass().getSimpleName() + ":\n" + rsps);
+ // short-circuit no-return-value calls.
+ if (rsps == null) return Collections.emptyList();
+ List<Object> retval = new ArrayList<Object>(rsps.size());
+ for (Rsp rsp : rsps.values())
+ {
+ if (rsp.wasSuspected() || !rsp.wasReceived())
{
- ex = new SuspectException("Suspected member: " + rsp.getSender());
+ CacheException ex;
+ if (rsp.wasSuspected())
+ {
+ ex = new SuspectException("Suspected member: " + rsp.getSender());
+ }
+ else
+ {
+ ex = new TimeoutException("Replication timeout for " + rsp.getSender());
+ }
+ retval.add(new ReplicationException("rsp=" + rsp, ex));
+ success = false;
}
else
{
- ex = new TimeoutException("Replication timeout for " + rsp.getSender());
+ Object value = rsp.getValue();
+ if (value instanceof Exception && !(value instanceof ReplicationException))
+ {
+ // if we have any application-level exceptions make sure we throw them!!
+ if (trace) log.trace("Recieved exception'" + value + "' from " + rsp.getSender());
+ throw (Exception) value;
+ }
+ retval.add(value);
+ success = true;
}
- retval.add(new ReplicationException("rsp=" + rsp, ex));
}
- else
- {
- Object value = rsp.getValue();
- if (value instanceof Exception && !(value instanceof ReplicationException))
- {
- // if we have any application-level exceptions make sure we throw them!!
- if (trace) log.trace("Recieved exception'" + value + "' from " + rsp.getSender());
- throw (Exception) value;
- }
- retval.add(value);
- }
+ return retval;
+ } catch (Exception e) {
+ success = false;
+ throw e;
+ } finally {
+ computeStats(success);
}
- return retval;
}
// ------------ START: Partial state transfer methods ------------
@@ -696,5 +702,58 @@
}
}
- /*------------------- End of MembershipListener ----------------------*/
+
+
+ //jmx operations
+ private void computeStats(boolean success) {
+ if (this.isStatisticsEnabled() && rpcDispatcher != null)
+ {
+ if (success)
+ {
+ replicationCount ++;
+ } else
+ {
+ replicationFailures ++;
+ }
+ }
+ }
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ this.replicationCount = 0;
+ this.replicationFailures = 0;
+ }
+
+ @ManagedAttribute(description = "number of successful replications")
+ public long getReplicationCount() {
+ return replicationCount;
+ }
+
+ @ManagedAttribute (description = "number of failed replications")
+ public long getReplicationFailures() {
+ return replicationFailures;
+ }
+
+ @ManagedAttribute (description = "whether or not jmx statistics are enabled")
+ public boolean isStatisticsEnabled() {
+ return statisticsEnabled;
+ }
+
+ @ManagedAttribute
+ public void setStatisticsEnabled(boolean statisticsEnabled) {
+ this.statisticsEnabled = statisticsEnabled;
+ }
+
+ @ManagedAttribute
+ public String getSuccessRatio()
+ {
+ if (replicationCount == 0 || !statisticsEnabled)
+ {
+ return "N/A";
+ }
+ double totalCount = replicationCount + replicationFailures;
+ double ration = (double)replicationCount / totalCount * 100d;
+ return NumberFormat.getInstance().format(ration) +"%";
+ }
}
\ No newline at end of file
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java 2008-08-07 19:23:46 UTC (rev 6543)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java 2008-08-08 09:37:39 UTC (rev 6544)
@@ -1,63 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors.base;
-
-import java.util.Map;
-
-/**
- * Interface containing common cache management operations
- *
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface JmxStatisticsInterceptor
-{
- /**
- * Returns whether an interceptor's statistics are
- * being captured.
- *
- * @return true if statistics are captured
- */
- boolean getStatisticsEnabled();
-
- /**
- * Enables an interceptor's cache statistics
- * If true, the interceptor will capture statistics
- * and make them available through the mbean.
- *
- * @param enabled true if statistics should be captured
- */
- void setStatisticsEnabled(boolean enabled);
-
- /**
- * Returns a map of the cache interceptor's statistics
- * Map is keyed on statistic names (which are Strings) and values are Objects.
- *
- * @return a map containing statistics
- */
- Map<String, Object> dumpStatistics();
-
- /**
- * Resets an interceptor's cache statistics
- */
- void resetStatistics();
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java 2008-08-07 19:23:46 UTC (rev 6543)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java 2008-08-08 09:37:39 UTC (rev 6544)
@@ -22,7 +22,7 @@
package org.jboss.cache.interceptors.base;
import org.jboss.cache.jmx.annotations.ManagedAttribute;
-import org.jboss.cache.interceptors.base.JmxStatisticsInterceptor;
+import org.jboss.cache.jmx.JmxStatisticsExposer;
import org.jboss.cache.factories.annotations.Start;
import java.util.Map;
@@ -34,7 +34,7 @@
* @author Mircea.Markus(a)jboss.com
* @since 3.0
*/
-public class JmxStatsCommandInterceptor extends CommandInterceptor implements JmxStatisticsInterceptor
+public class JmxStatsCommandInterceptor extends CommandInterceptor implements JmxStatisticsExposer
{
private boolean statsEnabled = false;
Copied: core/trunk/src/main/java/org/jboss/cache/jmx/JmxStatisticsExposer.java (from rev 6541, core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java)
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/JmxStatisticsExposer.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/JmxStatisticsExposer.java 2008-08-08 09:37:39 UTC (rev 6544)
@@ -0,0 +1,63 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx;
+
+import java.util.Map;
+
+/**
+ * Interface containing common cache management operations
+ *
+ * @author Jerry Gauthier
+ * @version $Id$
+ */
+public interface JmxStatisticsExposer
+{
+ /**
+ * Returns whether an interceptor's statistics are
+ * being captured.
+ *
+ * @return true if statistics are captured
+ */
+ boolean getStatisticsEnabled();
+
+ /**
+ * Enables an interceptor's cache statistics
+ * If true, the interceptor will capture statistics
+ * and make them available through the mbean.
+ *
+ * @param enabled true if statistics should be captured
+ */
+ void setStatisticsEnabled(boolean enabled);
+
+ /**
+ * Returns a map of the cache interceptor's statistics
+ * Map is keyed on statistic names (which are Strings) and values are Objects.
+ *
+ * @return a map containing statistics
+ */
+ Map<String, Object> dumpStatistics();
+
+ /**
+ * Resets an interceptor's cache statistics
+ */
+ void resetStatistics();
+}
Property changes on: core/trunk/src/main/java/org/jboss/cache/jmx/JmxStatisticsExposer.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-08-07 19:23:46 UTC (rev 6543)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-08-08 09:37:39 UTC (rev 6544)
@@ -22,13 +22,10 @@
package org.jboss.cache.jmx;
import org.jboss.cache.config.Configuration;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
-import org.jboss.cache.interceptors.base.JmxStatisticsInterceptor;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
-import java.util.List;
/**
* Various JMX related utilities
16 years, 5 months
JBoss Cache SVN: r6543 - core/trunk/src/main/java/org/jboss/cache/jmx.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-08-07 15:23:46 -0400 (Thu, 07 Aug 2008)
New Revision: 6543
Modified:
core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
Log:
fixed UT
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-08-07 19:05:04 UTC (rev 6542)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-08-07 19:23:46 UTC (rev 6543)
@@ -811,10 +811,6 @@
cache.addCacheListener(cacheNotificationListener);
}
}
- if (config != null)
- {
- this.registerJmxResource = config.getExposeManagementStatistics();
- }
}
public String getCacheObjectName()
@@ -940,7 +936,7 @@
protected boolean registerJmxResources() throws CacheException
{
- if (registerJmxResource && !jmxResourceRegistered && server != null)
+ if (registerJmxResource && config.getExposeManagementStatistics() && !jmxResourceRegistered && server != null)
{
log.debug("Registering jmx resources");
List<CommandInterceptor> interc = cache.getInterceptorChain();
16 years, 5 months
JBoss Cache SVN: r6542 - core/trunk/src/main/java/org/jboss/cache.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-08-07 15:05:04 -0400 (Thu, 07 Aug 2008)
New Revision: 6542
Modified:
core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
Log:
fixed wrong commit
Modified: core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-08-07 18:43:08 UTC (rev 6541)
+++ core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-08-07 19:05:04 UTC (rev 6542)
@@ -14,12 +14,8 @@
import org.jboss.cache.factories.ComponentFactory;
import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.invocation.CacheInvocationDelegate;
-import org.jboss.cache.jmx.MBeanRegistryHelper;
-import org.jboss.cache.jmx.CacheJmxWrapper;
-import org.jboss.cache.jmx.ResourceDMBean;
import java.io.InputStream;
-import java.util.Set;
/**
* Default implementation of the {@link org.jboss.cache.CacheFactory} interface.
@@ -127,10 +123,6 @@
this.configuration = configuration;
componentRegistry.registerComponent(spi, CacheSPI.class);
- if (configuration.getExposeManagementStatistics())
- {
- componentRegistry.registerComponent(new MBeanRegistryHelper(componentRegistry), MBeanRegistryHelper.class);
- }
}
/**
16 years, 5 months
JBoss Cache SVN: r6541 - in core/trunk/src: main/java/org/jboss/cache/factories and 6 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-08-07 14:43:08 -0400 (Thu, 07 Aug 2008)
New Revision: 6541
Added:
core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java
core/trunk/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java
core/trunk/src/main/java/org/jboss/cache/jmx/annotations/
core/trunk/src/main/java/org/jboss/cache/jmx/annotations/MBean.java
core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedAttribute.java
core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedOperation.java
core/trunk/src/test/java/org/jboss/cache/jmx/ResourceDMBeanTest.java
Removed:
core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptorMBean.java
core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptorMBean.java
Modified:
core/trunk/src/main/java/org/jboss/cache/CacheSPI.java
core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyActivationInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyCacheLoaderInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/base/CommandInterceptor.java
core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java
core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java
core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java
Log:
JBCACHE-1305 - JMX through annotations
Modified: core/trunk/src/main/java/org/jboss/cache/CacheSPI.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/CacheSPI.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/CacheSPI.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -18,6 +18,7 @@
import org.jboss.cache.statetransfer.StateTransferManager;
import org.jboss.cache.transaction.GlobalTransaction;
import org.jboss.cache.transaction.TransactionTable;
+import org.jboss.cache.factories.ComponentRegistry;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
@@ -329,4 +330,11 @@
* @return Set an unmodifiable set of children names, Object.
*/
Set<String> getChildrenNames(String fqn);
+
+ /**
+ * Returns the component registry associated with this cache instance.
+ *
+ * @see org.jboss.cache.factories.ComponentRegistry
+ */
+ ComponentRegistry getComponentRegistry();
}
Modified: core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/DefaultCacheFactory.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -14,8 +14,12 @@
import org.jboss.cache.factories.ComponentFactory;
import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.invocation.CacheInvocationDelegate;
+import org.jboss.cache.jmx.MBeanRegistryHelper;
+import org.jboss.cache.jmx.CacheJmxWrapper;
+import org.jboss.cache.jmx.ResourceDMBean;
import java.io.InputStream;
+import java.util.Set;
/**
* Default implementation of the {@link org.jboss.cache.CacheFactory} interface.
@@ -123,6 +127,10 @@
this.configuration = configuration;
componentRegistry.registerComponent(spi, CacheSPI.class);
+ if (configuration.getExposeManagementStatistics())
+ {
+ componentRegistry.registerComponent(new MBeanRegistryHelper(componentRegistry), MBeanRegistryHelper.class);
+ }
}
/**
Modified: core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/factories/ComponentRegistry.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -920,6 +920,16 @@
{
for (Method m : injectionMethods) invokeInjectionMethod(instance, m);
}
+
+ public Object getInstance()
+ {
+ return instance;
+ }
+
+ public String getName()
+ {
+ return name;
+ }
}
@@ -951,4 +961,13 @@
'}';
}
}
+
+ /**
+ * Returns an immutable set contating all the components that exists in the reporsitory at this moment.
+ */
+ public Set<Component> getRegiteredComponents()
+ {
+ HashSet<Component> defensiveCopy = new HashSet<Component>(componentLookup.values());
+ return Collections.unmodifiableSet(defensiveCopy);
+ }
}
Modified: core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -49,7 +49,6 @@
// wipe next/last chaining!!
chainedInterceptor.setNext(null);
}
- chainedInterceptor.setStatisticsEnabled(configuration.getExposeManagementStatistics());
return chainedInterceptor;
}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -3,6 +3,8 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.InternalNode;
import org.jboss.cache.Modification;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.commands.AbstractVisitor;
import org.jboss.cache.commands.read.GetChildrenNamesCommand;
import org.jboss.cache.commands.read.GetKeyValueCommand;
@@ -40,7 +42,7 @@
* @author <a href="mailto:{hmesha@novell.com}">{Hany Mesha}</a>
* @version $Id$
*/
-public class ActivationInterceptor extends CacheLoaderInterceptor implements ActivationInterceptorMBean
+public class ActivationInterceptor extends CacheLoaderInterceptor
{
protected TransactionManager txMgr = null;
@@ -263,30 +265,6 @@
}
}
- public long getActivations()
- {
- return activations;
- }
-
- @Override
- public void resetStatistics()
- {
- super.resetStatistics();
- activations = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = super.dumpStatistics();
- if (retval == null)
- {
- retval = new HashMap<String, Object>();
- }
- retval.put("Activations", activations);
- return retval;
- }
-
private void prepareCacheLoader(InvocationContext ctx) throws Throwable
{
GlobalTransaction gtx = ctx.getGlobalTransaction();
@@ -308,6 +286,7 @@
{
private List<Modification> cacheLoaderModifications = new ArrayList<Modification>();
+
private int txActs = 0;
@Override
@@ -387,5 +366,31 @@
{
return txActs;
}
+
}
+
+ @ManagedAttribute(description = "number of cache node activations")
+ public long getActivations()
+ {
+ return activations;
+ }
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ super.resetStatistics();
+ activations = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = super.dumpStatistics();
+ if (retval == null)
+ {
+ retval = new HashMap<String, Object>();
+ }
+ retval.put("Activations", activations);
+ return retval;
+ }
}
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/ActivationInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,38 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing activation statistics
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface ActivationInterceptorMBean extends CacheLoaderInterceptorMBean
-{
- /**
- * Returns the number of cache node activations
- *
- * @return the number of cache node activations
- */
- long getActivations();
-
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -5,6 +5,9 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.InternalNode;
import org.jboss.cache.NodeSPI;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
+import org.jboss.cache.jmx.annotations.MBean;
import org.jboss.cache.commands.read.GetChildrenNamesCommand;
import org.jboss.cache.commands.read.GetDataMapCommand;
import org.jboss.cache.commands.read.GetKeyValueCommand;
@@ -24,6 +27,7 @@
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.cache.interceptors.base.JmxStatsCommandInterceptor;
import org.jboss.cache.invocation.InvocationContext;
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.loader.CacheLoaderManager;
@@ -45,7 +49,7 @@
* @author Bela Ban
* @version $Id$
*/
-public class CacheLoaderInterceptor extends CommandInterceptor implements CacheLoaderInterceptorMBean
+public class CacheLoaderInterceptor extends JmxStatsCommandInterceptor
{
private long cacheLoads = 0;
private long cacheMisses = 0;
@@ -397,32 +401,6 @@
return false;
}
- public long getCacheLoaderLoads()
- {
- return cacheLoads;
- }
-
- public long getCacheLoaderMisses()
- {
- return cacheMisses;
- }
-
- @Override
- public void resetStatistics()
- {
- cacheLoads = 0;
- cacheMisses = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("CacheLoaderLoads", cacheLoads);
- retval.put("CacheLoaderMisses", cacheMisses);
- return retval;
- }
-
/**
* Loads a node from disk; if it exists creates parent TreeNodes.
* If it doesn't exist on disk but in memory, clears the
@@ -483,4 +461,31 @@
return nodeData;
}
+ @ManagedAttribute (description = "number of cache loader node loads")
+ public long getCacheLoaderLoads()
+ {
+ return cacheLoads;
+ }
+
+ @ManagedAttribute (description = "number of cache loader node misses")
+ public long getCacheLoaderMisses()
+ {
+ return cacheMisses;
+ }
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ cacheLoads = 0;
+ cacheMisses = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>();
+ retval.put("CacheLoaderLoads", cacheLoads);
+ retval.put("CacheLoaderMisses", cacheMisses);
+ return retval;
+ }
}
\ No newline at end of file
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,45 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing cache loader load statistics
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface CacheLoaderInterceptorMBean extends InterceptorMBean
-{
- /**
- * Returns the number of cache loader node loads
- *
- * @return the number of cache loader node loads
- */
- long getCacheLoaderLoads();
-
- /**
- * Returns the number of cache loader node misses
- *
- * @return the number of cache loader node misses
- */
- long getCacheLoaderMisses();
-
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -22,13 +22,15 @@
package org.jboss.cache.interceptors;
import org.jboss.cache.DataContainer;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.commands.read.GetKeyValueCommand;
import org.jboss.cache.commands.write.EvictCommand;
import org.jboss.cache.commands.write.PutDataMapCommand;
import org.jboss.cache.commands.write.PutForExternalReadCommand;
import org.jboss.cache.commands.write.PutKeyValueCommand;
import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.cache.interceptors.base.JmxStatsCommandInterceptor;
import org.jboss.cache.invocation.InvocationContext;
import java.util.HashMap;
@@ -40,17 +42,17 @@
* @author Jerry Gauthier
* @version $Id$
*/
-public class CacheMgmtInterceptor extends CommandInterceptor implements CacheMgmtInterceptorMBean
+public class CacheMgmtInterceptor extends JmxStatsCommandInterceptor
{
- private long m_hit_times = 0;
- private long m_miss_times = 0;
- private long m_store_times = 0;
- private long m_hits = 0;
- private long m_misses = 0;
- private long m_stores = 0;
- private long m_evictions = 0;
- private long m_start = System.currentTimeMillis();
- private long m_reset = m_start;
+ private long hitTimes = 0;
+ private long missTimes = 0;
+ private long storeTimes = 0;
+ private long hits = 0;
+ private long misses = 0;
+ private long stores = 0;
+ private long evictions = 0;
+ private long start = System.currentTimeMillis();
+ private long reset = start;
private DataContainer dataContainer;
@@ -64,7 +66,7 @@
public Object visitEvictFqnCommand(InvocationContext ctx, EvictCommand command) throws Throwable
{
Object returnValue = invokeNextInterceptor(ctx, command);
- m_evictions++;
+ evictions++;
return returnValue;
}
@@ -76,13 +78,13 @@
long t2 = System.currentTimeMillis();
if (retval == null)
{
- m_miss_times = m_miss_times + (t2 - t1);
- m_misses++;
+ missTimes = missTimes + (t2 - t1);
+ misses++;
}
else
{
- m_hit_times = m_hit_times + (t2 - t1);
- m_hits++;
+ hitTimes = hitTimes + (t2 - t1);
+ hits++;
}
return retval;
}
@@ -97,8 +99,8 @@
if (data != null && data.size() > 0)
{
- m_store_times = m_store_times + (t2 - t1);
- m_stores = m_stores + data.size();
+ storeTimes = storeTimes + (t2 - t1);
+ stores = stores + data.size();
}
return retval;
}
@@ -116,89 +118,101 @@
long t1 = System.currentTimeMillis();
Object retval = invokeNextInterceptor(ctx, command);
long t2 = System.currentTimeMillis();
- m_store_times = m_store_times + (t2 - t1);
- m_stores++;
+ storeTimes = storeTimes + (t2 - t1);
+ stores++;
return retval;
}
+ @ManagedAttribute(description = "number of cache attribute hits")
public long getHits()
{
- return m_hits;
+ return hits;
}
+ @ManagedAttribute (description = "number of cache attribute misses")
public long getMisses()
{
- return m_misses;
+ return misses;
}
+ @ManagedAttribute (description = "number of cache attribute put operations")
public long getStores()
{
- return m_stores;
+ return stores;
}
+ @ManagedAttribute (description = "number of cache eviction operations")
public long getEvictions()
{
- return m_evictions;
+ return evictions;
}
+ @ManagedAttribute (description = "hit/miss ratio for the cache")
public double getHitMissRatio()
{
- double total = m_hits + m_misses;
+ double total = hits + misses;
if (total == 0)
return 0;
- return (m_hits / total);
+ return (hits / total);
}
+ @ManagedAttribute (description = "read/writes ratio for the cache")
public double getReadWriteRatio()
{
- if (m_stores == 0)
+ if (stores == 0)
return 0;
- return (((double) (m_hits + m_misses) / (double) m_stores));
+ return (((double) (hits + misses) / (double) stores));
}
+ @ManagedAttribute (description = "average number of milliseconds for a read operation")
public long getAverageReadTime()
{
- long total = m_hits + m_misses;
+ long total = hits + misses;
if (total == 0)
return 0;
- return (m_hit_times + m_miss_times) / total;
+ return (hitTimes + missTimes) / total;
}
+ @ManagedAttribute (description = "average number of milliseconds for a write operation")
public long getAverageWriteTime()
{
- if (m_stores == 0)
+ if (stores == 0)
return 0;
- return (m_store_times) / m_stores;
+ return (storeTimes) / stores;
}
+ @ManagedAttribute (description = "number of cache eviction operations")
public int getNumberOfAttributes()
{
return dataContainer.getNumberOfAttributes();
}
+ @ManagedAttribute
public int getNumberOfNodes()
{
return dataContainer.getNumberOfNodes();
}
+ @ManagedAttribute (description = "seconds since cache started")
public long getElapsedTime()
{
- return (System.currentTimeMillis() - m_start) / 1000;
+ return (System.currentTimeMillis() - start) / 1000;
}
+ @ManagedAttribute (description = "number of seconds since the cache statistics were last reset")
public long getTimeSinceReset()
{
- return (System.currentTimeMillis() - m_reset) / 1000;
+ return (System.currentTimeMillis() - reset) / 1000;
}
- @Override
+ @ManagedOperation
public Map<String, Object> dumpStatistics()
{
Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("Hits", m_hits);
- retval.put("Misses", m_misses);
- retval.put("Stores", m_stores);
- retval.put("Evictions", m_evictions);
+ retval.put("Hits", hits);
+ retval.put("Misses", misses);
+ retval.put("Stores", stores);
+ retval.put("Evictions", evictions);
retval.put("NumberOfAttributes", dataContainer.getNumberOfAttributes());
retval.put("NumberOfNodes", dataContainer.getNumberOfNodes());
retval.put("ElapsedTime", getElapsedTime());
@@ -210,17 +224,17 @@
return retval;
}
- @Override
+ @ManagedOperation
public void resetStatistics()
{
- m_hits = 0;
- m_misses = 0;
- m_stores = 0;
- m_evictions = 0;
- m_hit_times = 0;
- m_miss_times = 0;
- m_store_times = 0;
- m_reset = System.currentTimeMillis();
+ hits = 0;
+ misses = 0;
+ stores = 0;
+ evictions = 0;
+ hitTimes = 0;
+ missTimes = 0;
+ storeTimes = 0;
+ reset = System.currentTimeMillis();
}
}
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,109 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing basic cache management statistics
- *
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface CacheMgmtInterceptorMBean extends InterceptorMBean
-{
- /**
- * Returns the number of cache attribute hits
- *
- * @return the number of cache hits
- */
- long getHits();
-
- /**
- * Returns the number of cache attribute misses
- *
- * @return the number of cache misses
- */
- long getMisses();
-
- /**
- * Returns the number of cache attribute put operations
- *
- * @return the number of cache put operations
- */
- long getStores();
-
- /**
- * Returns the number of cache eviction operations
- *
- * @return the number of cache eviction operations
- */
- long getEvictions();
-
- int getNumberOfAttributes();
-
- int getNumberOfNodes();
-
- /**
- * Returns the hit/miss ratio for the cache
- * This ratio is defined as hits/(hits + misses)
- *
- * @return the hit/miss ratio for the cache
- */
- double getHitMissRatio();
-
- /**
- * Returns the read/write ratio for the cache
- * This ratio is defined as (hits + misses)/stores
- *
- * @return the read/writes ratio for the cache
- */
- double getReadWriteRatio();
-
- /**
- * Returns average milliseconds for an attribute read operation
- * This includes both hits and misses.
- *
- * @return the average number of milliseconds for a read operation
- */
- long getAverageReadTime();
-
- /**
- * Returns average milliseconds for an attribute write operation
- *
- * @return the average number of milliseconds for a write operation
- */
- long getAverageWriteTime();
-
- /**
- * Returns seconds since cache started
- *
- * @return the number of seconds since the cache was started
- */
- long getElapsedTime();
-
- /**
- * Returns seconds since cache statistics reset
- * If statistics haven't been reset, this will be the same as ElapsedTime
- *
- * @return the number of seconds since the cache statistics were last reset
- */
- long getTimeSinceReset();
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -4,6 +4,8 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.Modification;
import org.jboss.cache.NodeSPI;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
import org.jboss.cache.commands.AbstractVisitor;
import org.jboss.cache.commands.VisitableCommand;
import org.jboss.cache.commands.WriteCommand;
@@ -46,7 +48,7 @@
* @author Bela Ban
* @version $Id$
*/
-public class CacheStoreInterceptor extends SkipCheckChainedInterceptor implements CacheStoreInterceptorMBean
+public class CacheStoreInterceptor extends SkipCheckChainedInterceptor
{
private CacheLoaderConfig loaderConfig = null;
private TransactionManager txMgr = null;
@@ -56,6 +58,7 @@
private CacheLoader loader;
private CacheLoaderManager loaderManager;
private boolean optimistic;
+ private boolean statsEnabled;
public CacheStoreInterceptor()
{
@@ -78,6 +81,7 @@
// this should only happen after the CacheLoaderManager has started, since the CacheLoaderManager only creates the CacheLoader instance in it's @Start method.
loader = loaderManager.getCacheLoader();
optimistic = configuration.getNodeLockingScheme() == NodeLockingScheme.OPTIMISTIC;
+ this.setStatisticsEnabled(configuration.getExposeManagementStatistics());
}
/**
@@ -317,25 +321,6 @@
}
}
- public long getCacheLoaderStores()
- {
- return cacheStores;
- }
-
- @Override
- public void resetStatistics()
- {
- cacheStores = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("CacheLoaderStores", cacheStores);
- return retval;
- }
-
private void prepareCacheLoader(GlobalTransaction gtx, TransactionContext transactionContext, boolean onePhase) throws Throwable
{
if (transactionContext == null)
@@ -372,9 +357,13 @@
public static class StoreModificationsBuilder extends AbstractVisitor
{
+
boolean generateStatistics;
+
int putCount;
+
Set<Fqn> affectedFqns = new HashSet<Fqn>();
+
List<Modification> modifications = new ArrayList<Modification>();
public StoreModificationsBuilder(boolean generateStatistics)
@@ -435,5 +424,39 @@
modifications.add(mod);
return null;
}
+
}
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ cacheStores = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>();
+ retval.put("CacheLoaderStores", cacheStores);
+ return retval;
+ }
+
+ @ManagedAttribute
+ public boolean getStatisticsEnabled()
+ {
+ return statsEnabled;
+ }
+
+ @ManagedAttribute
+ public void setStatisticsEnabled(boolean enabled)
+ {
+ this.statsEnabled = enabled;
+ }
+
+ @ManagedAttribute(description = "number of cache loader stores")
+ public long getCacheLoaderStores()
+ {
+ return cacheStores;
+ }
+
}
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/CacheStoreInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,38 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing cache loader statistics
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface CacheStoreInterceptorMBean extends InterceptorMBean
-{
- /**
- * Returns the number of cache loader stores
- *
- * @return the number of cache loader stores
- */
- long getCacheLoaderStores();
-
-}
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,63 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import java.util.Map;
-
-/**
- * Interface containing common cache management operations
- *
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface InterceptorMBean
-{
- /**
- * Returns whether an interceptor's statistics are
- * being captured.
- *
- * @return true if statistics are captured
- */
- boolean getStatisticsEnabled();
-
- /**
- * Enables an interceptor's cache statistics
- * If true, the interceptor will capture statistics
- * and make them available through the mbean.
- *
- * @param enabled true if statistics should be captured
- */
- void setStatisticsEnabled(boolean enabled);
-
- /**
- * Returns a map of the cache interceptor's statistics
- * Map is keyed on statistic names (which are Strings) and values are Objects.
- *
- * @return a map containing statistics
- */
- Map<String, Object> dumpStatistics();
-
- /**
- * Resets an interceptor's cache statistics
- */
- void resetStatistics();
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -7,6 +7,8 @@
package org.jboss.cache.interceptors;
import org.jboss.cache.Fqn;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
import org.jboss.cache.commands.AbstractVisitor;
import org.jboss.cache.commands.CommandsFactory;
import org.jboss.cache.commands.VisitableCommand;
@@ -60,12 +62,13 @@
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
-public class InvalidationInterceptor extends BaseRpcInterceptor implements InvalidationInterceptorMBean
+public class InvalidationInterceptor extends BaseRpcInterceptor
{
private long invalidations = 0;
protected Map<GlobalTransaction, List<WriteCommand>> txMods;
protected boolean optimistic;
private CommandsFactory commandsFactory;
+ private boolean statsEnabled;
@Inject
public void injectDependencies(CommandsFactory commandsFactory)
@@ -78,6 +81,7 @@
{
optimistic = configuration.getNodeLockingScheme() == NodeLockingScheme.OPTIMISTIC;
if (optimistic) txMods = new ConcurrentHashMap<GlobalTransaction, List<WriteCommand>>();
+ this.setStatisticsEnabled(configuration.getExposeManagementStatistics());
}
@Override
@@ -350,25 +354,6 @@
}
- public long getInvalidations()
- {
- return invalidations;
- }
-
- @Override
- public void resetStatistics()
- {
- invalidations = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("Invalidations", invalidations);
- return retval;
- }
-
protected void invalidateAcrossCluster(Fqn fqn, TransactionWorkspace workspace, boolean synchronous, InvocationContext ctx) throws Throwable
{
if (!isLocalModeForced(ctx))
@@ -410,4 +395,36 @@
OptimisticTransactionContext entry = (OptimisticTransactionContext) ctx.getTransactionContext();
return entry.getTransactionWorkSpace();
}
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ invalidations = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>();
+ retval.put("Invalidations", invalidations);
+ return retval;
+ }
+
+ @ManagedAttribute
+ public boolean getStatisticsEnabled()
+ {
+ return this.statsEnabled;
+ }
+
+ @ManagedAttribute
+ public void setStatisticsEnabled(boolean enabled)
+ {
+ this.statsEnabled = enabled;
+ }
+
+ @ManagedAttribute (description = "number of invalidations")
+ public long getInvalidations()
+ {
+ return invalidations;
+ }
}
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InvalidationInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,38 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing invalidation statistics
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface InvalidationInterceptorMBean extends InterceptorMBean
-{
- /**
- * Returns the number of cache invalidations
- *
- * @return the number of invalidations
- */
- long getInvalidations();
-
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -33,7 +33,7 @@
*
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
*/
-public class InvocationContextInterceptor extends BaseTransactionalContextInterceptor implements InvocationContextInterceptorMBean
+public class InvocationContextInterceptor extends BaseTransactionalContextInterceptor
{
private RPCManager rpcManager;
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,10 +0,0 @@
-package org.jboss.cache.interceptors;
-
-/**
- * MBean to the {@link InvocationContextInterceptor}
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
- */
-public interface InvocationContextInterceptorMBean extends InterceptorMBean
-{
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyActivationInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyActivationInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyActivationInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -3,6 +3,7 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.Modification;
import org.jboss.cache.NodeSPI;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.commands.AbstractVisitor;
import org.jboss.cache.commands.read.GetChildrenNamesCommand;
import org.jboss.cache.commands.read.GetKeyValueCommand;
@@ -42,7 +43,7 @@
* @deprecated will be removed along with optimistic and pessimistic locking.
*/
@Deprecated
-public class LegacyActivationInterceptor extends LegacyCacheLoaderInterceptor implements ActivationInterceptorMBean
+public class LegacyActivationInterceptor extends LegacyCacheLoaderInterceptor
{
protected TransactionManager txMgr = null;
@@ -270,25 +271,6 @@
return activations;
}
- @Override
- public void resetStatistics()
- {
- super.resetStatistics();
- activations = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = super.dumpStatistics();
- if (retval == null)
- {
- retval = new HashMap<String, Object>();
- }
- retval.put("Activations", activations);
- return retval;
- }
-
private void prepareCacheLoader(InvocationContext ctx) throws Throwable
{
GlobalTransaction gtx = ctx.getGlobalTransaction();
@@ -310,6 +292,7 @@
{
private List<Modification> cacheLoaderModifications = new ArrayList<Modification>();
+
private int txActs = 0;
@Override
@@ -389,5 +372,25 @@
{
return txActs;
}
+
}
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ super.resetStatistics();
+ activations = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = super.dumpStatistics();
+ if (retval == null)
+ {
+ retval = new HashMap<String, Object>();
+ }
+ retval.put("Activations", activations);
+ return retval;
+ }
}
\ No newline at end of file
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyCacheLoaderInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyCacheLoaderInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/LegacyCacheLoaderInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -5,26 +5,18 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.WriteCommand;
-import org.jboss.cache.commands.read.GetChildrenNamesCommand;
-import org.jboss.cache.commands.read.GetDataMapCommand;
-import org.jboss.cache.commands.read.GetKeyValueCommand;
-import org.jboss.cache.commands.read.GetKeysCommand;
-import org.jboss.cache.commands.read.GetNodeCommand;
+import org.jboss.cache.commands.read.*;
import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.commands.write.ClearDataCommand;
-import org.jboss.cache.commands.write.MoveCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutForExternalReadCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.commands.write.RemoveKeyCommand;
-import org.jboss.cache.commands.write.RemoveNodeCommand;
+import org.jboss.cache.commands.write.*;
import org.jboss.cache.config.Configuration;
import static org.jboss.cache.config.Configuration.CacheMode;
import org.jboss.cache.config.Configuration.NodeLockingScheme;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.Start;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.cache.interceptors.base.JmxStatsCommandInterceptor;
import org.jboss.cache.invocation.InvocationContext;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.lock.LockManager;
@@ -34,12 +26,7 @@
import org.jboss.cache.transaction.TransactionContext;
import org.jboss.cache.transaction.TransactionTable;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
/**
* Loads nodes that don't exist at the time of the call into memory from the CacheLoader
@@ -49,7 +36,7 @@
* @deprecated will be removed along with optimistic and pessimistic locking.
*/
@Deprecated
-public class LegacyCacheLoaderInterceptor extends CommandInterceptor implements CacheLoaderInterceptorMBean
+public class LegacyCacheLoaderInterceptor extends JmxStatsCommandInterceptor
{
private long cacheLoads = 0;
private long cacheMisses = 0;
@@ -430,32 +417,6 @@
return false;
}
- public long getCacheLoaderLoads()
- {
- return cacheLoads;
- }
-
- public long getCacheLoaderMisses()
- {
- return cacheMisses;
- }
-
- @Override
- public void resetStatistics()
- {
- cacheLoads = 0;
- cacheMisses = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("CacheLoaderLoads", cacheLoads);
- retval.put("CacheLoaderMisses", cacheMisses);
- return retval;
- }
-
protected void lock(Fqn fqn, LockType lockType, boolean recursive, InvocationContext ctx) throws Throwable
{
if (configuration.getNodeLockingScheme() == NodeLockingScheme.OPTIMISTIC) return;
@@ -582,4 +543,32 @@
return nodeData;
}
+ @ManagedAttribute(description = "number of cache loader node loads")
+ public long getCacheLoaderLoads()
+ {
+ return cacheLoads;
+ }
+
+ @ManagedAttribute(description = "number of cache loader node misses")
+ public long getCacheLoaderMisses()
+ {
+ return cacheMisses;
+ }
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ cacheLoads = 0;
+ cacheMisses = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>();
+ retval.put("CacheLoaderLoads", cacheLoads);
+ retval.put("CacheLoaderMisses", cacheMisses);
+ return retval;
+ }
+
}
\ No newline at end of file
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -4,8 +4,11 @@
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.write.EvictCommand;
import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.cache.factories.annotations.Start;
+import org.jboss.cache.interceptors.base.JmxStatsCommandInterceptor;
import org.jboss.cache.invocation.InvocationContext;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.notifications.Notifier;
@@ -22,7 +25,7 @@
* @author <a href="mailto:{hmesha@novell.com}">{Hany Mesha}</a>
* @version $Id$
*/
-public class PassivationInterceptor extends CommandInterceptor implements PassivationInterceptorMBean
+public class PassivationInterceptor extends JmxStatsCommandInterceptor
{
private final AtomicLong passivations = new AtomicLong(0);
@@ -80,25 +83,6 @@
}
}
- public long getPassivations()
- {
- return passivations.get();
- }
-
- @Override
- public void resetStatistics()
- {
- passivations.set(0);
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("Passivations", passivations.get());
- return retval;
- }
-
/**
* Returns attributes for a node.
*/
@@ -122,9 +106,31 @@
private static class NodeNotLoadedException extends Exception
{
+
/**
* The serialVersionUID
*/
private static final long serialVersionUID = -4078972305344328905L;
+
}
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ passivations.set(0);
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>();
+ retval.put("Passivations", passivations.get());
+ return retval;
+ }
+
+ @ManagedAttribute (description = "number of cache node passivations")
+ public long getPassivations()
+ {
+ return passivations.get();
+ }
}
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/PassivationInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,38 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing passivation statistics
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface PassivationInterceptorMBean extends InterceptorMBean
-{
- /**
- * Returns the number of cache node passivations
- *
- * @return the number of cache node passivations
- */
- long getPassivations();
-
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -9,6 +9,9 @@
import org.jboss.cache.CacheException;
import org.jboss.cache.RPCManager;
import org.jboss.cache.ReplicationException;
+import org.jboss.cache.jmx.annotations.MBean;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.commands.AbstractVisitor;
import org.jboss.cache.commands.CommandsFactory;
import org.jboss.cache.commands.ReplicableCommand;
@@ -58,7 +61,7 @@
* @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
* @author <a href="mailto:stevew@jofti.com">Steve Woodcock (stevew(a)jofti.com)</a>
*/
-public class TxInterceptor extends BaseTransactionalContextInterceptor implements TxInterceptorMBean
+public class TxInterceptor extends BaseTransactionalContextInterceptor
{
protected CommandsFactory commandsFactory;
protected RPCManager rpcManager;
@@ -77,6 +80,7 @@
private long rollbacks = 0;
protected boolean optimistic = false;
private LockManager lockManager;
+ private boolean statsEnabled;
@Inject
public void intialize(RPCManager rpcManager, ContextFactory contextFactory,
@@ -90,6 +94,7 @@
this.invocationContextContainer = icc;
this.componentRegistry = componentRegistry;
this.lockManager = lockManager;
+ setStatisticsEnabled(configuration.getExposeManagementStatistics());
}
@Override
@@ -270,39 +275,6 @@
// JMX statistics
// ------------------------------------------------------------------------
- public long getPrepares()
- {
- return prepares;
- }
-
- public long getCommits()
- {
- return commits;
- }
-
- public long getRollbacks()
- {
- return rollbacks;
- }
-
- @Override
- public void resetStatistics()
- {
- prepares = 0;
- commits = 0;
- rollbacks = 0;
- }
-
- @Override
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>(3);
- retval.put("Prepares", prepares);
- retval.put("Commits", commits);
- retval.put("Rollbacks", rollbacks);
- return retval;
- }
-
// --------------------------------------------------------------
/**
@@ -1131,4 +1103,52 @@
return "TxInterceptor.LocalSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
}
}
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ prepares = 0;
+ commits = 0;
+ rollbacks = 0;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>(3);
+ retval.put("Prepares", prepares);
+ retval.put("Commits", commits);
+ retval.put("Rollbacks", rollbacks);
+ return retval;
+ }
+
+ @ManagedAttribute
+ public boolean getStatisticsEnabled()
+ {
+ return this.statsEnabled;
+ }
+
+ @ManagedAttribute
+ public void setStatisticsEnabled(boolean enabled)
+ {
+ this.statsEnabled = enabled;
+ }
+
+ @ManagedAttribute (description = "number of transaction prepares")
+ public long getPrepares()
+ {
+ return prepares;
+ }
+
+ @ManagedAttribute (description = "number of transaction commits")
+ public long getCommits()
+ {
+ return commits;
+ }
+
+ @ManagedAttribute (description = "number of transaction rollbacks")
+ public long getRollbacks()
+ {
+ return rollbacks;
+ }
}
\ No newline at end of file
Deleted: core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptorMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptorMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/TxInterceptorMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -1,52 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005, JBoss Inc., and individual contributors as indicated
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-/**
- * Interface capturing transaction statistics
- * @author Jerry Gauthier
- * @version $Id$
- */
-public interface TxInterceptorMBean extends InterceptorMBean
-{
- /**
- * Returns the number of transaction prepares
- *
- * @return the number of prepares
- */
- long getPrepares();
-
- /**
- * Returns the number of transaction commits
- *
- * @return the number of commits
- */
- long getCommits();
-
- /**
- * Returns the number of transaction rollbacks
- *
- * @return the number of rollbacks
- */
- long getRollbacks();
-
-}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/base/CommandInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/base/CommandInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/base/CommandInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -6,13 +6,8 @@
import org.jboss.cache.commands.VisitableCommand;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.factories.annotations.Inject;
-import org.jboss.cache.factories.annotations.Start;
-import org.jboss.cache.interceptors.InterceptorMBean;
import org.jboss.cache.invocation.InvocationContext;
-import java.util.Collections;
-import java.util.Map;
-
/**
* This is the base class for all interceptors to extend, and implements the {@link org.jboss.cache.commands.Visitor} interface
* allowing it to intercept invocations on {@link org.jboss.cache.commands.VisitableCommand}s.
@@ -36,9 +31,9 @@
* @see org.jboss.cache.interceptors.InterceptorChain
* @since 2.2
*/
-public class CommandInterceptor extends AbstractVisitor implements InterceptorMBean
+public class CommandInterceptor extends AbstractVisitor
{
- private boolean statsEnabled = false;
+
private CommandInterceptor next;
@@ -59,47 +54,7 @@
this.configuration = configuration;
}
- @Start
- private void checkStatisticsUsed()
- {
- setStatisticsEnabled(configuration.getExposeManagementStatistics());
- }
-
/**
- * @return true if gathering statistics for JMX is enabled on this interceptor.
- */
- public boolean getStatisticsEnabled()
- {
- return statsEnabled;
- }
-
- /**
- * @param enabled whether gathering statistics for JMX are enabled.
- */
- public void setStatisticsEnabled(boolean enabled)
- {
- statsEnabled = enabled;
- }
-
- /**
- * Returns a map of statistics. This is a default implementation which returns an empty map and should be overridden
- * if it is to be meaningful.
- *
- * @return an empty map
- */
- public Map<String, Object> dumpStatistics()
- {
- return Collections.emptyMap();
- }
-
- /**
- * Resets statistics gathered. Is a no-op, and should be overridden if it is to be meaningful.
- */
- public void resetStatistics()
- {
- }
-
- /**
* Retrieves the next interceptor in the chain.
*
* @return the next interceptor in the chain.
Copied: core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java (from rev 6532, core/trunk/src/main/java/org/jboss/cache/interceptors/InterceptorMBean.java)
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,63 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.interceptors.base;
+
+import java.util.Map;
+
+/**
+ * Interface containing common cache management operations
+ *
+ * @author Jerry Gauthier
+ * @version $Id$
+ */
+public interface JmxStatisticsInterceptor
+{
+ /**
+ * Returns whether an interceptor's statistics are
+ * being captured.
+ *
+ * @return true if statistics are captured
+ */
+ boolean getStatisticsEnabled();
+
+ /**
+ * Enables an interceptor's cache statistics
+ * If true, the interceptor will capture statistics
+ * and make them available through the mbean.
+ *
+ * @param enabled true if statistics should be captured
+ */
+ void setStatisticsEnabled(boolean enabled);
+
+ /**
+ * Returns a map of the cache interceptor's statistics
+ * Map is keyed on statistic names (which are Strings) and values are Objects.
+ *
+ * @return a map containing statistics
+ */
+ Map<String, Object> dumpStatistics();
+
+ /**
+ * Resets an interceptor's cache statistics
+ */
+ void resetStatistics();
+}
Property changes on: core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatisticsInterceptor.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Added: core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/base/JmxStatsCommandInterceptor.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,87 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.interceptors.base;
+
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.interceptors.base.JmxStatisticsInterceptor;
+import org.jboss.cache.factories.annotations.Start;
+
+import java.util.Map;
+import java.util.Collections;
+
+/**
+ * Base class for all the interceptors exposing management statistics.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ * @since 3.0
+ */
+public class JmxStatsCommandInterceptor extends CommandInterceptor implements JmxStatisticsInterceptor
+{
+ private boolean statsEnabled = false;
+
+ @Start
+ public void checkStatisticsUsed()
+ {
+ setStatisticsEnabled(configuration.getExposeManagementStatistics());
+ }
+
+ /**
+ * Returns whether an interceptor's statistics are
+ * being captured.
+ *
+ * @return true if statistics are captured
+ */
+ @ManagedAttribute
+ public boolean getStatisticsEnabled()
+ {
+ return statsEnabled;
+ }
+
+ /**
+ * @param enabled whether gathering statistics for JMX are enabled.
+ */
+ @ManagedAttribute
+ public void setStatisticsEnabled(boolean enabled)
+ {
+ statsEnabled = enabled;
+ }
+
+ /**
+ * Returns a map of statistics. This is a default implementation which returns an empty map and should be overridden
+ * if it is to be meaningful.
+ *
+ * @return an empty map
+ */
+ public Map<String, Object> dumpStatistics()
+ {
+ return Collections.emptyMap();
+ }
+
+ /**
+ * Resets statistics gathered. Is a no-op, and should be overridden if it is to be meaningful.
+ */
+ public void resetStatistics()
+ {
+ }
+
+
+}
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -38,6 +38,7 @@
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.factories.annotations.Start;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.marshall.Marshaller;
@@ -619,6 +620,11 @@
return (Set) getChildrenNames(Fqn.fromString(fqn));
}
+ public ComponentRegistry getComponentRegistry()
+ {
+ return componentRegistry;
+ }
+
public DataContainer getDataContainer()
{
return dataContainer;
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -24,6 +24,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.*;
+import org.jboss.cache.factories.ComponentRegistry;
import org.jboss.cache.config.*;
import org.jboss.cache.config.parsing.JGroupsStackParser;
import org.jboss.cache.config.parsing.element.BuddyElementParser;
@@ -40,6 +41,7 @@
import javax.management.*;
import javax.transaction.TransactionManager;
import java.util.List;
+import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -59,10 +61,10 @@
private MBeanServer server;
private String cacheObjectName;
- private boolean interceptorsRegistered;
+ private boolean jmxResourceRegistered;
private CacheSPI<K, V> cache;
private Configuration config;
- private boolean registerInterceptors = true;
+ private boolean registerJmxResource = true;
private final AtomicInteger listenerCount = new AtomicInteger(0);
private final AtomicLong sequence = new AtomicLong(0);
private final CacheNotificationListener cacheNotificationListener;
@@ -83,6 +85,7 @@
private LoadersElementParser loadersElementParser = new LoadersElementParser();
private EvictionElementParser evictionElementParser = new EvictionElementParser();
private JGroupsStackParser stackParser = new JGroupsStackParser();
+ private List<ResourceDMBean> resourceDMBeans = new ArrayList<ResourceDMBean>();
// ----------------------------------------------------------- Constructors
@@ -198,14 +201,14 @@
return cache == null ? "Cache is null" : formatHtml(CachePrinter.printCacheLockingInfo(cache));
}
- public boolean getRegisterInterceptors()
+ public boolean getRegisterJmxResource()
{
- return registerInterceptors;
+ return registerJmxResource;
}
- public void setRegisterInterceptors(boolean register)
+ public void setRegisterJmxResource(boolean register)
{
- this.registerInterceptors = register;
+ this.registerJmxResource = register;
}
// ---------------------------------------------------- LegacyConfiguration
@@ -607,7 +610,7 @@
cache.start();
- registerInterceptors();
+ registerJmxResources();
cacheStatus = CacheStatus.STARTED;
sendStateChangeNotification(startingState, getState(), getClass().getSimpleName() + " started", null);
@@ -640,8 +643,8 @@
if (cache.getCacheStatus() == CacheStatus.DESTROYED)
{
// Cache was already destroyed externally;
- // so get rid of the interceptor mbeans
- unregisterInterceptors();
+ // so get rid of the jmx resources
+ unregisterJmxResources();
}
cacheStatus = CacheStatus.STOPPED;
@@ -682,9 +685,9 @@
{
cacheStatus = CacheStatus.DESTROYING;
- // The cache is destroyed, so we shouldn't leave the interceptors
+ // The cache is destroyed, so we shouldn't leave the ResourcesDMBean
// in JMX, even if we didn't register them in create
- unregisterInterceptors();
+ unregisterJmxResources();
if (cache != null)
cache.destroy();
@@ -725,12 +728,11 @@
if (notificationServiceName == null)
notificationServiceName = result.getCanonicalName();
cacheNotificationListener.setServiceName(notificationServiceName);
-
return result;
}
/**
- * Registers the cache's interceptors, if {@link #getRegisterInterceptors()}
+ * Registers the cache's MBean resources, if {@link #getRegisterJmxResource()}
* is <code>true</code>.
*/
public void postRegister(Boolean registrationDone)
@@ -738,16 +740,15 @@
if (Boolean.TRUE.equals(registrationDone))
{
log.debug("Registered in JMX under " + cacheObjectName);
-
if (cache != null && CacheStatus.STARTED.equals(cache.getCacheStatus()))
{
try
{
- registerInterceptors();
+ registerJmxResources();
}
catch (Exception e)
{
- log.error("Caught exception registering cache interceptors with JMX", e);
+ log.error("Caught exception registering cache ResourcesDMBean with JMX", e);
}
}
@@ -763,12 +764,12 @@
}
/**
- * Unregisters the interceptors, if {@link #getRegisterInterceptors()} is
+ * Unregisters the ResourcesDMBean, if {@link #getRegisterJmxResource()} is
* <code>true</code>.
*/
public void postDeregister()
{
- unregisterInterceptors();
+ unregisterJmxResources();
server = null;
registered = false;
@@ -810,6 +811,10 @@
cache.addCacheListener(cacheNotificationListener);
}
}
+ if (config != null)
+ {
+ this.registerJmxResource = config.getExposeManagementStatistics();
+ }
}
public String getCacheObjectName()
@@ -933,38 +938,56 @@
}
}
- protected boolean registerInterceptors() throws CacheException
+ protected boolean registerJmxResources() throws CacheException
{
- if (registerInterceptors && !interceptorsRegistered && server != null)
+ if (registerJmxResource && !jmxResourceRegistered && server != null)
{
- log.debug("Registering interceptors");
+ log.debug("Registering jmx resources");
List<CommandInterceptor> interc = cache.getInterceptorChain();
if (interc != null && interc.size() > 0)
{
try
{
- JmxUtil.registerInterceptors(server, interc, cacheObjectName);
- interceptorsRegistered = true;
+ for (ComponentRegistry.Component component : cache.getComponentRegistry().getRegiteredComponents())
+ {
+ ResourceDMBean resourceDMBean = new ResourceDMBean(component.getInstance());
+ if (resourceDMBean.isManagedResource())
+ {
+ resourceDMBeans.add(resourceDMBean);
+ }
+ }
+ for (ResourceDMBean resource: resourceDMBeans)
+ {
+ String resourceName = resource.getObject().getClass().getSimpleName();
+ ObjectName objectName = new ObjectName(cacheObjectName + JmxUtil.JMX_RESOURCE_KEY + resourceName);
+ if (!server.isRegistered(objectName)) server.registerMBean(resource, objectName);
+ }
+ jmxResourceRegistered = true;
return true;
}
catch (JMException e)
{
- throw new CacheException("Failed to register interceptors", e);
+ throw new CacheException("Failed to register jmx resources", e);
}
}
}
return false;
}
- protected void unregisterInterceptors()
+ protected void unregisterJmxResources()
{
- if (registerInterceptors && interceptorsRegistered && server != null)
+ if (registerJmxResource && jmxResourceRegistered && server != null)
{
try
{
log.debug("Unregistering interceptors");
- JmxUtil.unregisterInterceptors(server, cache.getInterceptorChain(), getCacheObjectName());
- interceptorsRegistered = false;
+ for (ResourceDMBean resource : resourceDMBeans)
+ {
+ String resourceName = resource.getObject().getClass().getSimpleName();
+ ObjectName objectName = new ObjectName(cacheObjectName + JmxUtil.JMX_RESOURCE_KEY + resourceName);
+ if (server.isRegistered(objectName)) server.unregisterMBean(objectName);
+ }
+ jmxResourceRegistered = false;
}
catch (Exception e)
{
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/CacheJmxWrapperMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -164,7 +164,7 @@
* <p/>
* Default is <code>true</code>.
*/
- boolean getRegisterInterceptors();
+ boolean getRegisterJmxResource();
/**
* Sets whether this object should register the cache's interceptors
@@ -172,5 +172,5 @@
* <p/>
* Default is <code>true</code>.
*/
- void setRegisterInterceptors(boolean register);
+ void setRegisterJmxResource(boolean register);
}
Modified: core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/JmxUtil.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -23,6 +23,7 @@
import org.jboss.cache.config.Configuration;
import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.cache.interceptors.base.JmxStatisticsInterceptor;
import javax.management.JMException;
import javax.management.MBeanServer;
@@ -49,7 +50,7 @@
public static final String CACHE_TYPE_KEY = "cacheType";
public static final String PLAIN_CACHE_TYPE = "Cache";
public static final String MBEAN_CLASS_SUFFIX = "MBean";
- public static final String INTERCEPTOR_KEY = ",cache-interceptor=";
+ public static final String JMX_RESOURCE_KEY = ",jmx-resource=";
public static void registerCacheMBean(MBeanServer server, CacheJmxWrapperMBean cache, String cacheObjectName)
throws JMException
@@ -61,58 +62,6 @@
}
}
- /*
- * Register the associated mbeans for cache interceptors
- *
- * @param server the mbean server with which the mbeans should be registered
- * @param cache the cache having the set of interceptors to be registered
- * @param registerCache whether the cache itself should be registered
- */
- public static void registerInterceptors(MBeanServer server, List<CommandInterceptor> interceptors, String cacheObjectName)
- throws JMException
- {
- if (server == null || interceptors == null || cacheObjectName == null)
- {
- return;
- }
-
- for (CommandInterceptor interceptor : interceptors)
- {
- if (!interceptor.getStatisticsEnabled())
- continue;
-
- boolean mbeanExists = true;
- try
- {
- // the mbean for interceptor AbcInterceptor will be named AbcInterceptorMBean
- Class.forName(interceptor.getClass().getName() + MBEAN_CLASS_SUFFIX);
- }
- catch (Throwable e)
- {
- // if the class can't be instantiated, no mbean is available
- mbeanExists = false;
- }
-
- // for JDK 1.4, must parse name and remove package prefix
- // for JDK 1.5, can use getSimpleName() to establish class name without package prefix
- String className = interceptor.getClass().getName();
- String serviceName = cacheObjectName + INTERCEPTOR_KEY + className.substring(className.lastIndexOf('.') + 1);
-
- ObjectName objName = new ObjectName(serviceName);
- if (!server.isRegistered(objName))
- {
- if (mbeanExists)
- // register associated interceptor mbean
- {
- server.registerMBean(interceptor, objName);
- }
- //else
- // register dummy interceptor mbean
- // server.registerMBean(new BaseInterceptor(), objName);
- }
- }
- }
-
public static String getDefaultCacheObjectName(org.jboss.cache.Cache cache)
{
// get the cache's registration name
@@ -131,7 +80,6 @@
{
tmpName = PREFIX + config.getClusterName();
}
-
return tmpName;
}
@@ -145,34 +93,4 @@
{
server.unregisterMBean(new ObjectName(cacheObjectName));
}
-
- /*
- * Unregister the associated mbeans for cache interceptors
- *
- * @param server the mbean server for which the mbeans should be unregistered
- * @param cache the cache having the set of interceptors to be unregistered
- * @param unregisterCache whether the cache itself should be unregistered
- */
- public static void unregisterInterceptors(MBeanServer server, List<CommandInterceptor> interceptors, String cacheObjectName)
- throws Exception
- {
- if (server == null || interceptors == null || cacheObjectName == null)
- {
- return;
- }
-
- for (CommandInterceptor interceptor : interceptors)
- {
- // for JDK 1.4, must parse name and remove package prefix
- // for JDK 1.5, can use getSimpleName() to establish class name without package prefix
- String className = interceptor.getClass().getName();
- String serviceName = cacheObjectName + INTERCEPTOR_KEY + className.substring(className.lastIndexOf('.') + 1);
-
- ObjectName objName = new ObjectName(serviceName);
- if (server.isRegistered(objName))
- {
- server.unregisterMBean(objName);
- }
- }
- }
}
Added: core/trunk/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,734 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.jmx.annotations.MBean;
+import org.jboss.cache.jmx.annotations.ManagedAttribute;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
+
+import javax.management.*;
+import java.util.HashMap;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.regex.Pattern;
+import java.util.regex.Matcher;
+import java.lang.reflect.Method;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+
+/**
+ * This class was entirely copied from jgroups (same name there).
+ * Couldn't simply reuse it because jgroups does not ship with MBean, ManagedAttribute and ManagedOperation.
+ * Once jgroups will ship these classes, the code can be dinalmically reused from there.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ * @since 3.0
+ */
+public class ResourceDMBean implements DynamicMBean
+{
+ private static final Class<?>[] primitives = {int.class,
+ byte.class,
+ short.class,
+ long.class,
+ float.class,
+ double.class,
+ boolean.class,
+ char.class};
+
+ private static final String MBEAN_DESCRITION = "Dynamic MBean Description";
+
+ private final Log log = LogFactory.getLog(ResourceDMBean.class);
+ private final Object obj;
+ private String description = "";
+
+ private final MBeanAttributeInfo[] attrInfo;
+ private final MBeanOperationInfo[] opInfo;
+
+ private final HashMap<String, AttributeEntry> atts = new HashMap<String, AttributeEntry>();
+ private final List<MBeanOperationInfo> ops = new ArrayList<MBeanOperationInfo>();
+
+ public ResourceDMBean(Object instance)
+ {
+
+ if (instance == null)
+ throw new NullPointerException("Cannot make an MBean wrapper for null instance");
+
+ this.obj = instance;
+ findDescription();
+ findFields();
+ findMethods();
+
+ attrInfo = new MBeanAttributeInfo[atts.size()];
+ int i = 0;
+ log.info("Processing class " + instance.getClass());
+ log.info("Attributes are:");
+ MBeanAttributeInfo info = null;
+ for (AttributeEntry entry : atts.values())
+ {
+ info = entry.getInfo();
+ attrInfo[i++] = info;
+ log.info("Attribute " + info.getName()
+ + "[r="
+ + info.isReadable()
+ + ",w="
+ + info.isWritable()
+ + ",is="
+ + info.isIs()
+ + ",type="
+ + info.getType()
+ + "]");
+ }
+
+ opInfo = new MBeanOperationInfo[ops.size()];
+ ops.toArray(opInfo);
+
+ if (ops.size() > 0)
+ log.info("Operations are:");
+ for (MBeanOperationInfo op : opInfo)
+ {
+ log.info("Operation " + op.getReturnType() + " " + op.getName());
+ }
+
+ }
+
+ Object getObject()
+ {
+ return obj;
+ }
+
+ private void findDescription()
+ {
+ MBean mbean = getObject().getClass().getAnnotation(MBean.class);
+ if (mbean != null && mbean.description() != null && mbean.description().trim().length() > 0)
+ {
+ description = mbean.description();
+ if (log.isDebugEnabled())
+ {
+ log.debug("@MBean description set - " + mbean.description());
+ }
+ MBeanAttributeInfo info = new MBeanAttributeInfo(MBEAN_DESCRITION,
+ "java.lang.String",
+ "@MBean description",
+ true,
+ false,
+ false);
+ try
+ {
+ atts.put(MBEAN_DESCRITION,
+ new FieldAttributeEntry(info, getClass().getDeclaredField("description")));
+ }
+ catch (NoSuchFieldException e)
+ {
+ //this should not happen unless somebody removes description field
+ log.warn("Could not reflect field description of this class. Was it removed?");
+ }
+ }
+ }
+
+ public synchronized MBeanInfo getMBeanInfo()
+ {
+
+ return new MBeanInfo(getObject().getClass().getCanonicalName(),
+ description,
+ attrInfo,
+ null,
+ opInfo,
+ null);
+ }
+
+ public synchronized Object getAttribute(String name)
+ {
+ if (name == null || name.length() == 0)
+ throw new NullPointerException("Invalid attribute requested " + name);
+
+ if (log.isDebugEnabled())
+ {
+ log.debug("getAttribute called for " + name);
+ }
+ Attribute attr = getNamedAttribute(name);
+ if (log.isDebugEnabled())
+ {
+ log.debug("getAttribute value found " + attr.getValue());
+ }
+ return attr.getValue();
+ }
+
+ public synchronized void setAttribute(Attribute attribute)
+ {
+ if (attribute == null || attribute.getName() == null)
+ throw new NullPointerException("Invalid attribute requested " + attribute);
+
+ setNamedAttribute(attribute);
+ }
+
+ public synchronized AttributeList getAttributes(String[] names)
+ {
+ AttributeList al = new AttributeList();
+ for (String name : names)
+ {
+ Attribute attr = getNamedAttribute(name);
+ if (attr != null)
+ {
+ al.add(attr);
+ }
+ else
+ {
+ log.warn("Did not find attribute " + name);
+ }
+ }
+ return al;
+ }
+
+ public synchronized AttributeList setAttributes(AttributeList list)
+ {
+ AttributeList results = new AttributeList();
+ for (int i = 0; i < list.size(); i++)
+ {
+ Attribute attr = (Attribute) list.get(i);
+
+ if (log.isDebugEnabled())
+ {
+ log.debug("Attribute name " + attr.getName() + " new value is " + attr.getValue());
+ }
+
+ if (setNamedAttribute(attr))
+ {
+ results.add(attr);
+ }
+ else
+ {
+ if (log.isWarnEnabled())
+ {
+ log.debug("Failed to update attribute name " + attr.getName()
+ + " with value "
+ + attr.getValue());
+ }
+ }
+ }
+ return results;
+ }
+
+ public Object invoke(String name, Object[] args, String[] sig) throws MBeanException,
+ ReflectionException
+ {
+ try
+ {
+ if (log.isDebugEnabled())
+ {
+ log.debug("Invoke method called on " + name);
+ }
+ Class<?>[] classes = new Class[sig.length];
+ for (int i = 0; i < classes.length; i++)
+ {
+ classes[i] = getClassForName(sig[i]);
+ }
+ Method method = getObject().getClass().getMethod(name, classes);
+ return method.invoke(getObject(), args);
+ }
+ catch (Exception e)
+ {
+ throw new MBeanException(e);
+ }
+ }
+
+ public static Class<?> getClassForName(String name) throws ClassNotFoundException
+ {
+ try
+ {
+ Class<?> c = Class.forName(name);
+ return c;
+ }
+ catch (ClassNotFoundException cnfe)
+ {
+ //Could be a primitive - let's check
+ for (int i = 0; i < primitives.length; i++)
+ {
+ if (name.equals(primitives[i].getName()))
+ {
+ return primitives[i];
+ }
+ }
+ }
+ throw new ClassNotFoundException("Class " + name + " cannot be found");
+ }
+
+ private void findMethods()
+ {
+ //find all methods but don't include methods from Object class
+ List<Method> methods = new ArrayList<Method>(Arrays.asList(getObject().getClass().getMethods()));
+ List<Method> objectMethods = new ArrayList<Method>(Arrays.asList(Object.class.getMethods()));
+ methods.removeAll(objectMethods);
+
+ for (Method method : methods)
+ {
+ //does method have @ManagedAttribute annotation?
+ ManagedAttribute attr = method.getAnnotation(ManagedAttribute.class);
+ if (attr != null)
+ {
+ String methodName = method.getName();
+ if (!methodName.startsWith("get") && !methodName.startsWith("set")
+ && !methodName.startsWith("is"))
+ {
+ if (log.isWarnEnabled())
+ log.warn("method name " + methodName
+ + " doesn't start with \"get\", \"set\", or \"is\""
+ + ", but is annotated with @ManagedAttribute: will be ignored");
+ }
+ else
+ {
+ MBeanAttributeInfo info = null;
+ //Is name field of @ManagedAttributed used?
+ String attributeName = attr.name().length() > 0 ? attr.name().trim() : null;
+ boolean writeAttribute = false;
+ if (isSetMethod(method))
+ { // setter
+ attributeName = (attributeName == null) ? methodName.substring(3) : attributeName;
+ info = new MBeanAttributeInfo(attributeName,
+ method.getParameterTypes()[0].getCanonicalName(),
+ attr.description(),
+ true,
+ true,
+ false);
+ writeAttribute = true;
+ }
+ else
+ { // getter
+ if (method.getParameterTypes().length == 0 && method.getReturnType() != java.lang.Void.TYPE)
+ {
+ boolean hasSetter = atts.containsKey(attributeName);
+ //we found is method
+ if (methodName.startsWith("is"))
+ {
+ attributeName = (attributeName == null) ? methodName.substring(2) : attributeName;
+ info = new MBeanAttributeInfo(attributeName,
+ method.getReturnType().getCanonicalName(),
+ attr.description(),
+ true,
+ hasSetter,
+ true);
+ }
+ else
+ {
+ //this has to be get
+ attributeName = (attributeName == null) ? methodName.substring(3) : attributeName;
+ info = new MBeanAttributeInfo(attributeName,
+ method.getReturnType().getCanonicalName(),
+ attr.description(),
+ true,
+ hasSetter,
+ false);
+ }
+ }
+ else
+ {
+ if (log.isWarnEnabled())
+ {
+ log.warn("Method " + method.getName()
+ + " must have a valid return type and zero parameters");
+ }
+ continue;
+ }
+ }
+
+ if (log.isDebugEnabled())
+ {
+ log.debug("@Attr found for method " + method.getName() + " and registered as " + attributeName);
+ }
+
+ AttributeEntry ae = atts.get(attributeName);
+ //is it a read method?
+ if (!writeAttribute)
+ {
+ //we already have annotated field as read
+ if (ae instanceof FieldAttributeEntry && ae.getInfo().isReadable())
+ {
+ log.warn("not adding annotated method " + method
+ + " since we already have read attribute");
+ }
+ //we already have annotated set method
+ else if (ae instanceof MethodAttributeEntry)
+ {
+ MethodAttributeEntry mae = (MethodAttributeEntry) ae;
+ if (mae.hasSetMethod())
+ {
+ atts.put(attributeName,
+ new MethodAttributeEntry(mae.getInfo(), mae.getSetMethod(), method));
+ }
+ } //we don't have such entry
+ else
+ {
+ atts.put(attributeName, new MethodAttributeEntry(info, null, method));
+ }
+ }//is it a set method?
+ else
+ {
+ if (ae instanceof FieldAttributeEntry)
+ {
+ //we already have annotated field as write
+ if (ae.getInfo().isWritable())
+ {
+ log.warn("Not adding annotated method " + methodName
+ + " since we already have writable attribute");
+ }
+ else
+ {
+ //we already have annotated field as read
+ //lets make the field writable
+ Field f = ((FieldAttributeEntry) ae).getField();
+ MBeanAttributeInfo i = new MBeanAttributeInfo(ae.getInfo().getName(),
+ f.getType().getCanonicalName(),
+ attr.description(),
+ true,
+ Modifier.isFinal(f.getModifiers()) ? false : true,
+ false);
+ atts.put(attributeName, new FieldAttributeEntry(i, f));
+ }
+ }
+ //we already have annotated getOrIs method
+ else if (ae instanceof MethodAttributeEntry)
+ {
+ MethodAttributeEntry mae = (MethodAttributeEntry) ae;
+ if (mae.hasIsOrGetMethod())
+ {
+ atts.put(attributeName,
+ new MethodAttributeEntry(info,
+ method,
+ mae.getIsOrGetMethod()));
+ }
+ } //we don't have such entry
+ else
+ {
+ atts.put(attributeName, new MethodAttributeEntry(info, method, null));
+ }
+ }
+ }
+ }
+ else if (method.isAnnotationPresent(ManagedOperation.class) || isMBeanAnnotationPresentWithExposeAll())
+ {
+ ManagedOperation op = method.getAnnotation(ManagedOperation.class);
+ String attName = method.getName();
+ if (isSetMethod(method) || isGetMethod(method))
+ {
+ attName = attName.substring(3);
+ }
+ else if (isIsMethod(method))
+ {
+ attName = attName.substring(2);
+ }
+ //expose unless we already exposed matching attribute field
+ boolean isAlreadyExposed = atts.containsKey(attName);
+ if (!isAlreadyExposed)
+ {
+ ops.add(new MBeanOperationInfo(op != null ? op.description() : "", method));
+ if (log.isDebugEnabled())
+ {
+ log.debug("@Operation found for method " + method.getName());
+ }
+ }
+ }
+ }
+ }
+
+ private boolean isSetMethod(Method method)
+ {
+ return (method.getName().startsWith("set") &&
+ method.getParameterTypes().length == 1 &&
+ method.getReturnType() == java.lang.Void.TYPE);
+ }
+
+ private boolean isGetMethod(Method method)
+ {
+ return (method.getParameterTypes().length == 0 &&
+ method.getReturnType() != java.lang.Void.TYPE &&
+ method.getName().startsWith("get"));
+ }
+
+ private boolean isIsMethod(Method method)
+ {
+ return (method.getParameterTypes().length == 0 &&
+ (method.getReturnType() == boolean.class || method.getReturnType() == Boolean.class) &&
+ method.getName().startsWith("is"));
+ }
+
+ private void findFields()
+ {
+ //traverse class hierarchy and find all annotated fields
+ for (Class<?> clazz = getObject().getClass(); clazz != null; clazz = clazz.getSuperclass())
+ {
+
+ Field[] fields = clazz.getDeclaredFields();
+ for (Field field : fields)
+ {
+ ManagedAttribute attr = field.getAnnotation(ManagedAttribute.class);
+ if (attr != null)
+ {
+ String fieldName = renameToJavaCodingConvention(field.getName());
+ MBeanAttributeInfo info = new MBeanAttributeInfo(fieldName,
+ field.getType().getCanonicalName(),
+ attr.description(),
+ true,
+ Modifier.isFinal(field.getModifiers()) ? false : attr.writable(),
+ false);
+
+ atts.put(fieldName, new FieldAttributeEntry(info, field));
+ if (log.isDebugEnabled())
+ {
+ log.debug("@Attr found for field " + field.getName());
+ }
+ }
+ }
+ }
+ }
+
+ private Attribute getNamedAttribute(String name)
+ {
+ Attribute result = null;
+ if (name.equals(MBEAN_DESCRITION))
+ {
+ result = new Attribute(MBEAN_DESCRITION, this.description);
+ }
+ else
+ {
+ AttributeEntry entry = atts.get(name);
+ if (entry != null)
+ {
+ MBeanAttributeInfo i = entry.getInfo();
+ try
+ {
+ result = new Attribute(name, entry.invoke(null));
+ if (log.isDebugEnabled())
+ log.debug("Attribute " + name
+ + " has r="
+ + i.isReadable()
+ + ",w="
+ + i.isWritable()
+ + ",is="
+ + i.isIs()
+ + " and value "
+ + result.getValue());
+ }
+ catch (Exception e)
+ {
+ log.debug("Exception while reading value of attribute " + name, e);
+ }
+ }
+ else
+ {
+ log.warn("Did not find queried attribute with name " + name);
+ }
+ }
+ return result;
+ }
+
+ private boolean setNamedAttribute(Attribute attribute)
+ {
+ boolean result = false;
+ if (log.isDebugEnabled())
+ log.debug("Invoking set on attribute " + attribute.getName()
+ + " with value "
+ + attribute.getValue());
+
+ AttributeEntry entry = atts.get(attribute.getName());
+ if (entry != null)
+ {
+ try
+ {
+ entry.invoke(attribute);
+ result = true;
+ }
+ catch (Exception e)
+ {
+ log.warn("Exception while writing value for attribute " + attribute.getName(), e);
+ }
+ }
+ else
+ {
+ log.warn("Could not invoke set on attribute " + attribute.getName()
+ + " with value "
+ + attribute.getValue());
+ }
+ return result;
+ }
+
+
+ private String renameToJavaCodingConvention(String fieldName)
+ {
+ if (fieldName.contains("_"))
+ {
+ Pattern p = Pattern.compile("_.");
+ Matcher m = p.matcher(fieldName);
+ StringBuffer sb = new StringBuffer();
+ while (m.find())
+ {
+ m.appendReplacement(sb, fieldName.substring(m.end() - 1, m.end()).toUpperCase());
+ }
+ m.appendTail(sb);
+ char first = sb.charAt(0);
+ if (Character.isLowerCase(first))
+ {
+ sb.setCharAt(0, Character.toUpperCase(first));
+ }
+ return sb.toString();
+ }
+ else
+ {
+ if (Character.isLowerCase(fieldName.charAt(0)))
+ {
+ return fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
+ }
+ else
+ {
+ return fieldName;
+ }
+ }
+ }
+
+ private boolean isMBeanAnnotationPresentWithExposeAll()
+ {
+ Class<?> c = getObject().getClass();
+ return c.isAnnotationPresent(MBean.class) && c.getAnnotation(MBean.class).exposeAll();
+ }
+
+ private class MethodAttributeEntry implements AttributeEntry
+ {
+
+ final MBeanAttributeInfo info;
+
+ final Method isOrGetmethod;
+
+ final Method setMethod;
+
+ public MethodAttributeEntry(final MBeanAttributeInfo info,
+ final Method setMethod,
+ final Method isOrGetMethod)
+ {
+ super();
+ this.info = info;
+ this.setMethod = setMethod;
+ this.isOrGetmethod = isOrGetMethod;
+ }
+
+ public Object invoke(Attribute a) throws Exception
+ {
+ if (a == null && isOrGetmethod != null)
+ return isOrGetmethod.invoke(getObject(), new Object[]{});
+ else if (a != null && setMethod != null)
+ return setMethod.invoke(getObject(), new Object[]{a.getValue()});
+ else
+ return null;
+ }
+
+ public MBeanAttributeInfo getInfo()
+ {
+ return info;
+ }
+
+ public boolean hasIsOrGetMethod()
+ {
+ return isOrGetmethod != null;
+ }
+
+ public boolean hasSetMethod()
+ {
+ return setMethod != null;
+ }
+
+ public Method getIsOrGetMethod()
+ {
+ return isOrGetmethod;
+ }
+
+ public Method getSetMethod()
+ {
+ return setMethod;
+ }
+ }
+
+ private class FieldAttributeEntry implements AttributeEntry
+ {
+
+ private final MBeanAttributeInfo info;
+
+ private final Field field;
+
+ public FieldAttributeEntry(final MBeanAttributeInfo info, final Field field)
+ {
+ super();
+ this.info = info;
+ this.field = field;
+ if (!field.isAccessible())
+ {
+ field.setAccessible(true);
+ }
+ }
+
+ public Field getField()
+ {
+ return field;
+ }
+
+ public Object invoke(Attribute a) throws Exception
+ {
+ if (a == null)
+ {
+ return field.get(getObject());
+ }
+ else
+ {
+ field.set(getObject(), a.getValue());
+ return null;
+ }
+ }
+
+ public MBeanAttributeInfo getInfo()
+ {
+ return info;
+ }
+ }
+
+ private interface AttributeEntry
+ {
+ public Object invoke(Attribute a) throws Exception;
+
+ public MBeanAttributeInfo getInfo();
+ }
+
+ public boolean isManagedResource()
+ {
+ return !atts.isEmpty() || !ops.isEmpty();
+ }
+
+ public boolean isOperationRegistred(String operationName)
+ {
+ for (MBeanOperationInfo opInfo : this.ops)
+ {
+ if (opInfo.getName().equals(operationName))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+}
Added: core/trunk/src/main/java/org/jboss/cache/jmx/annotations/MBean.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/annotations/MBean.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/annotations/MBean.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx.annotations;
+
+import java.lang.annotation.*;
+
+/**
+ * Classes anotaded with this will be exposed as MBeans.
+ * If you are looking for more fined grained way of exposing jmx attributes/operations, take a look at
+ * {@link org.jboss.cache.jmx.annotations.ManagedAttribute} and {@link org.jboss.cache.jmx.annotations.ManagedOperation}
+ *
+ * @author Mircea.Markus(a)jboss.com
+ * @since 3.0
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+@Target( { ElementType.TYPE })
+@Inherited
+public @interface MBean
+{
+ String objectName() default "";
+ boolean exposeAll() default false;
+ String description() default "";
+}
Added: core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedAttribute.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedAttribute.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedAttribute.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx.annotations;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+
+/**
+ * Indicates that a public method or a field (any visibility) in
+ * an MBean class defines an MBean attribute. This annotation can
+ * be applied to either a field or a public setter and/or getter
+ * method of a public class that is itself is optionally annotated
+ * with an @MBean annotation, or inherits such an annotation from
+ * a superclass.
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+(a)Target({ElementType.METHOD, ElementType.FIELD})
+public @interface ManagedAttribute
+{
+ String description() default "";
+
+ String name() default "";
+
+ boolean writable() default false;
+}
Added: core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedOperation.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedOperation.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/jmx/annotations/ManagedOperation.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,41 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx.annotations;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.lang.annotation.ElementType;
+
+/**
+ * Indicates that a method in an MBean class defines an MBean
+ * operation. @ManagedOperation annotation can be applied to a
+ * public method of a public class that is itself optionally
+ * annotated with an @MBean annotation, or inherits such an
+ * annotation from a superclass.
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+(a)Target({ElementType.METHOD})
+public @interface ManagedOperation
+{
+ String description() default "";
+}
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/CacheJmxWrapperTestBase.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -156,9 +156,8 @@
{
// should be 3 interceptor MBeans loaded:
ObjectName[] interceptorMBeanNames = {
- new ObjectName(baseName + JmxUtil.INTERCEPTOR_KEY + "TxInterceptor"),
- new ObjectName(baseName + JmxUtil.INTERCEPTOR_KEY + "CacheMgmtInterceptor"),
- new ObjectName(baseName + JmxUtil.INTERCEPTOR_KEY + "InvocationContextInterceptor")
+ new ObjectName(baseName + JmxUtil.JMX_RESOURCE_KEY + "TxInterceptor"),
+ new ObjectName(baseName + JmxUtil.JMX_RESOURCE_KEY + "CacheMgmtInterceptor"),
};
for (ObjectName n : interceptorMBeanNames)
Modified: core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java 2008-08-07 16:45:39 UTC (rev 6540)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/InterceptorRegistrationTest.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -277,7 +277,7 @@
public void testRegisterInterceptors1() throws Exception
{
CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- wrapper.setRegisterInterceptors(false);
+ wrapper.setRegisterJmxResource(false);
registerWrapper(wrapper);
@@ -308,7 +308,7 @@
public void testRegisterInterceptors2() throws Exception
{
CacheJmxWrapper<String, String> wrapper = createWrapper(createConfiguration());
- wrapper.setRegisterInterceptors(false);
+ wrapper.setRegisterJmxResource(false);
wrapper.create();
wrapper.start();
Added: core/trunk/src/test/java/org/jboss/cache/jmx/ResourceDMBeanTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/jmx/ResourceDMBeanTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/jmx/ResourceDMBeanTest.java 2008-08-07 18:43:08 UTC (rev 6541)
@@ -0,0 +1,59 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.jmx;
+
+import org.testng.annotations.Test;
+import org.jboss.cache.interceptors.ActivationInterceptor;
+import org.jboss.cache.jmx.annotations.ManagedOperation;
+
+/**
+ * Tester class for {@link ResourceDMBean}.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ * @since 3.0
+ */
+@Test (groups = "unit")
+public class ResourceDMBeanTest
+{
+
+ /**
+ * If we have a method in the base class that is annotated as @ManagedOperation, will this be seen the same
+ * way in the inherited class?
+ */
+ public void testInheritedMethod()
+ {
+ Bbb bbb = new Bbb();
+ ResourceDMBean resourceDMBean = new ResourceDMBean(bbb);
+ assert resourceDMBean.isOperationRegistred("baseMethod");
+ }
+
+ static class Aaa
+ {
+ @ManagedOperation
+ public void baseMethod() {}
+ }
+
+ static class Bbb extends Aaa
+ {
+ public void localMethod() {}
+ }
+}
16 years, 5 months
JBoss Cache SVN: r6540 - in core/trunk/src: main/java/org/jboss/cache/batch and 12 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-08-07 12:45:39 -0400 (Thu, 07 Aug 2008)
New Revision: 6540
Added:
core/trunk/src/main/java/org/jboss/cache/batch/
core/trunk/src/main/java/org/jboss/cache/batch/BatchContainer.java
core/trunk/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java
core/trunk/src/test/java/org/jboss/cache/api/batch/
core/trunk/src/test/java/org/jboss/cache/api/batch/AbstractBatchTest.java
core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithTM.java
core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithoutTM.java
Modified:
core/trunk/src/main/java/org/jboss/cache/Cache.java
core/trunk/src/main/java/org/jboss/cache/CacheSPI.java
core/trunk/src/main/java/org/jboss/cache/config/Configuration.java
core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java
core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java
core/trunk/src/main/java/org/jboss/cache/interceptors/OptimisticLockingInterceptor.java
core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
core/trunk/src/main/java/org/jboss/cache/transaction/BatchModeTransactionManagerLookup.java
core/trunk/src/main/resources/jbosscache-config-3.0.xsd
core/trunk/src/test/java/org/jboss/cache/config/parsing/XmlConfigurationParserTest.java
core/trunk/src/test/java/org/jboss/cache/factories/InterceptorChainFactoryTest.java
core/trunk/src/test/resources/configs/parser-test.xml
Log:
JBCACHE-991 - Batching API
Modified: core/trunk/src/main/java/org/jboss/cache/Cache.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/Cache.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/Cache.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -495,4 +495,30 @@
*/
void clearData(Fqn fqn);
+ /**
+ * Starts a batch. This is a lightweight batching mechanism that groups cache writes together and finally performs the
+ * write, persistence and/or replication when {@link #endBatch(boolean)} is called rather than for each invocation on the
+ * cache.
+ * <p/>
+ * Note that if there is an existing transaction in scope and the cache has been configured to use a JTA compliant
+ * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as no-ops.
+ * <p/>
+ *
+ * @see #endBatch(boolean)
+ * @since 3.0
+ */
+ void startBatch();
+
+ /**
+ * Ends an existing ongoing batch. A no-op if a batch has not been started yet.
+ * <p/>
+ * Note that if there is an existing transaction in scope and the cache has been configured to use a JTA compliant
+ * transaction manager, calls to {@link #startBatch()} and {@link #endBatch(boolean)} are ignored and treated as no-ops.
+ * <p/>
+ *
+ * @param successful if <tt>true</tt>, changes made in the batch are committed. If <tt>false</tt>, they are discarded.
+ * @see #startBatch()
+ * @since 3.0
+ */
+ void endBatch(boolean successful);
}
Modified: core/trunk/src/main/java/org/jboss/cache/CacheSPI.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/CacheSPI.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/CacheSPI.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -39,7 +39,6 @@
* @see NodeSPI
* @see Cache
* @see org.jboss.cache.loader.CacheLoader
- * @see org.jboss.cache.interceptors.ChainedInterceptor
* @since 2.0.0
*/
@ThreadSafe
Added: core/trunk/src/main/java/org/jboss/cache/batch/BatchContainer.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/batch/BatchContainer.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/batch/BatchContainer.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -0,0 +1,80 @@
+package org.jboss.cache.batch;
+
+import org.jboss.cache.CacheException;
+import org.jboss.cache.factories.annotations.Inject;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+/**
+ * A container for holding thread locals for batching, to be used with the {@link org.jboss.cache.Cache#startBatch()} and
+ * {@link org.jboss.cache.Cache#endBatch(boolean)} calls.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class BatchContainer
+{
+ TransactionManager transactionManager;
+ private ThreadLocal<Transaction> batchTransactionContainer = new ThreadLocal<Transaction>();
+
+ @Inject
+ void inject(TransactionManager transactionManager)
+ {
+ this.transactionManager = transactionManager;
+ }
+
+ public void startBatch() throws CacheException
+ {
+ try
+ {
+ if (transactionManager.getTransaction() != null) return;
+ if (batchTransactionContainer.get() == null)
+ {
+ transactionManager.begin();
+ batchTransactionContainer.set(transactionManager.suspend());
+ }
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to start batch", e);
+ }
+ }
+
+ public void endBatch(boolean success)
+ {
+ Transaction tx = batchTransactionContainer.get();
+ if (tx == null) return;
+ Transaction existingTx = null;
+ try
+ {
+ existingTx = transactionManager.getTransaction();
+ transactionManager.resume(tx);
+ if (success)
+ tx.commit();
+ else
+ tx.rollback();
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to end batch", e);
+ }
+ finally
+ {
+ batchTransactionContainer.remove();
+ try
+ {
+ if (existingTx != null) transactionManager.resume(existingTx);
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Failed resuming existing transaction " + existingTx, e);
+ }
+ }
+ }
+
+ public Transaction getBatchTransaction()
+ {
+ return batchTransactionContainer.get();
+ }
+}
Modified: core/trunk/src/main/java/org/jboss/cache/config/Configuration.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/Configuration.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/config/Configuration.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -32,6 +32,7 @@
private Marshaller marshaller;
private JGroupsStackParser jGroupsStackParser = new JGroupsStackParser();
+ private boolean invocationBatchingEnabled;
/**
* Behavior of the JVM shutdown hook registered by the cache
@@ -299,6 +300,19 @@
this.exposeManagementStatistics = useMbean;
}
+ /**
+ * Enables invocation batching if set to <tt>true</tt>. You still need to use {@link org.jboss.cache.Cache#startBatch()}
+ * and {@link org.jboss.cache.Cache#endBatch(boolean)} to demarcate the start and end of batches.
+ *
+ * @param enabled if true, batching is enabled.
+ * @since 3.0
+ */
+ public void setInvocationBatchingEnabled(boolean enabled)
+ {
+ testImmutability("invocationBatchingEnabled");
+ this.invocationBatchingEnabled = enabled;
+ }
+
public void setFetchInMemoryState(boolean fetchInMemoryState)
{
testImmutability("fetchInMemoryState");
@@ -652,6 +666,15 @@
return exposeManagementStatistics;
}
+ /**
+ * @return true if invocation batching is enabled.
+ * @since 3.0
+ */
+ public boolean isInvocationBatchingEnabled()
+ {
+ return invocationBatchingEnabled;
+ }
+
public boolean isFetchInMemoryState()
{
return fetchInMemoryState;
Modified: core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/config/parsing/XmlConfigurationParser.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -52,8 +52,8 @@
* <p/>
* Following system properties can be used for customizing parser behavior:
* <ul>
- * <li> <b>-Djbosscache.config.validate=false</b> will make the parser non-validating </li>
- * <li> <b>-Djbosscache.config.schemaLocation=url</b> allows one to specify a validation schema that would override the one specified in the the xml document </li>
+ * <li> <b>-Djbosscache.config.validate=false</b> will make the parser non-validating </li>
+ * <li> <b>-Djbosscache.config.schemaLocation=url</b> allows one to specify a validation schema that would override the one specified in the the xml document </li>
* </ul>
* This class is stateful and one instance should be used for parsing a single configuration file.
*
@@ -173,6 +173,7 @@
configureCacheLoaders(getSingleElement("loaders"));
configureCustomInterceptors(getSingleElement("customInterceptors"));
configureListeners(getSingleElement("listeners"));
+ configureInvocationBatching(getSingleElement("invocationBatching"));
}
catch (Exception e)
{
@@ -248,6 +249,13 @@
}
}
+ private void configureInvocationBatching(Element element)
+ {
+ if (element == null) return; //this element is optional
+ boolean enabled = getBoolean(getAttributeValue(element, "enabled"));
+ config.setInvocationBatchingEnabled(enabled);
+ }
+
private void configureBuddyReplication(Element element)
{
if (element == null) return;//buddy config might not exist, expect that
Modified: core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/factories/EmptyConstructorFactory.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -2,6 +2,7 @@
import org.jboss.cache.DataContainer;
import org.jboss.cache.RegionRegistry;
+import org.jboss.cache.batch.BatchContainer;
import org.jboss.cache.buddyreplication.BuddyFqnTransformer;
import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.factories.annotations.DefaultFactoryFor;
@@ -25,7 +26,7 @@
@DefaultFactoryFor(classes = {Notifier.class, MVCCNodeHelper.class, RegionRegistry.class,
ChannelMessageListener.class, CacheLoaderManager.class, Marshaller.class, InvocationContextContainer.class,
CacheInvocationDelegate.class, TransactionTable.class, DataContainer.class,
- LockStrategyFactory.class, BuddyFqnTransformer.class})
+ LockStrategyFactory.class, BuddyFqnTransformer.class, BatchContainer.class})
public class EmptyConstructorFactory extends ComponentFactory
{
@Override
Modified: core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/factories/InterceptorChainFactory.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -56,13 +56,18 @@
public InterceptorChain buildInterceptorChain() throws IllegalAccessException, InstantiationException, ClassNotFoundException
{
boolean optimistic = configuration.getNodeLockingScheme() == NodeLockingScheme.OPTIMISTIC;
+ boolean invocationBatching = configuration.isInvocationBatchingEnabled();
// load the icInterceptor first
- CommandInterceptor first = createInterceptor(InvocationContextInterceptor.class);
+ CommandInterceptor first = invocationBatching ? createInterceptor(BatchingInterceptor.class) : createInterceptor(InvocationContextInterceptor.class);
InterceptorChain interceptorChain = new InterceptorChain(first);
// add the interceptor chain to the registry first, since some interceptors may ask for it.
componentRegistry.registerComponent(interceptorChain, InterceptorChain.class);
+ // NOW add the ICI if we are using batching!
+ if (invocationBatching)
+ interceptorChain.appendIntereceptor(createInterceptor(InvocationContextInterceptor.class));
+
// load the cache management interceptor next
if (configuration.getExposeManagementStatistics())
interceptorChain.appendIntereceptor(createInterceptor(CacheMgmtInterceptor.class));
Modified: core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/factories/TransactionManagerFactory.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -2,6 +2,7 @@
import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.factories.annotations.DefaultFactoryFor;
+import org.jboss.cache.transaction.BatchModeTransactionManager;
import org.jboss.cache.transaction.TransactionManagerLookup;
import javax.transaction.TransactionManager;
@@ -52,6 +53,12 @@
log.info("failed looking up TransactionManager, will not use transactions", e);
}
}
+
+ if (transactionManager == null && configuration.isInvocationBatchingEnabled())
+ {
+ log.info("Using a batchMode transaction manager");
+ transactionManager = BatchModeTransactionManager.getInstance();
+ }
return componentType.cast(transactionManager);
}
}
Added: core/trunk/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java (rev 0)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -0,0 +1,58 @@
+package org.jboss.cache.interceptors;
+
+import org.jboss.cache.batch.BatchContainer;
+import org.jboss.cache.commands.VisitableCommand;
+import org.jboss.cache.factories.annotations.Inject;
+import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.cache.invocation.InvocationContext;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+/**
+ * Interceptor that captures batched calls and attaches contexts.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class BatchingInterceptor extends CommandInterceptor
+{
+ BatchContainer batchContainer;
+ TransactionManager transactionManager;
+
+ @Inject
+ private void inject(BatchContainer batchContainer, TransactionManager transactionManager)
+ {
+ this.batchContainer = batchContainer;
+ this.transactionManager = transactionManager;
+ }
+
+ /**
+ * Simply check if there is an ongoing tx.
+ * <ul>
+ * <li>If there is one, this is a no-op and just passes the call up the chain.</li>
+ * <li>If there isn't one and there is a batch in progress, resume the batch's tx, pass up, and finally suspend the batch's tx.</li>
+ * <li>If there is no batch in progress, just pass the call up the chain.</li>
+ * </ul>
+ */
+ @Override
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
+ {
+ Transaction tx = null;
+ try
+ {
+ // if in a batch, attach tx
+ if (transactionManager.getTransaction() == null &&
+ (tx = batchContainer.getBatchTransaction()) != null)
+ {
+ transactionManager.resume(tx);
+ }
+ return super.handleDefault(ctx, command);
+ }
+ finally
+ {
+ if (tx != null && transactionManager.getTransaction() != null)
+ transactionManager.suspend();
+ }
+ }
+}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/OptimisticLockingInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/OptimisticLockingInterceptor.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/OptimisticLockingInterceptor.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -18,6 +18,7 @@
import static org.jboss.cache.lock.LockType.WRITE;
import org.jboss.cache.optimistic.TransactionWorkspace;
import org.jboss.cache.optimistic.WorkspaceNode;
+import org.jboss.cache.transaction.BatchModeTransactionManager;
import org.jboss.cache.transaction.GlobalTransaction;
import org.jboss.cache.transaction.TransactionContext;
@@ -35,7 +36,7 @@
@Start
private void init()
{
- if (txManager == null)
+ if (txManager == null || txManager.getClass().equals(BatchModeTransactionManager.class))
log.fatal("No transaction manager lookup class has been defined. Transactions cannot be used and thus OPTIMISTIC locking cannot be used! Expect errors!!");
}
Modified: core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -1,13 +1,5 @@
package org.jboss.cache.invocation;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.CacheException;
@@ -21,6 +13,7 @@
import org.jboss.cache.Region;
import org.jboss.cache.RegionManager;
import org.jboss.cache.Version;
+import org.jboss.cache.batch.BatchContainer;
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.buddyreplication.GravitateResult;
import org.jboss.cache.commands.CommandsFactory;
@@ -39,8 +32,9 @@
import org.jboss.cache.commands.write.RemoveKeyCommand;
import org.jboss.cache.commands.write.RemoveNodeCommand;
import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.Configuration.NodeLockingScheme;
+import org.jboss.cache.config.ConfigurationException;
import org.jboss.cache.config.Option;
-import org.jboss.cache.config.Configuration.NodeLockingScheme;
import org.jboss.cache.factories.annotations.Inject;
import org.jboss.cache.factories.annotations.NonVolatile;
import org.jboss.cache.factories.annotations.Start;
@@ -55,6 +49,13 @@
import org.jboss.cache.util.Immutables;
import org.jgroups.Address;
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
/**
* The delegate that users (and ChainedInterceptor authors) interact with when they create a cache by using a cache factory.
* This wrapper delegates calls down the interceptor chain.
@@ -81,12 +82,13 @@
private CommandsFactory commandsFactory;
private MVCCNodeHelper mvccHelper;
private boolean usingMvcc;
+ private BatchContainer batchContainer;
@Inject
public void initialize(StateTransferManager stateTransferManager, CacheLoaderManager cacheLoaderManager, Notifier notifier,
TransactionManager transactionManager, BuddyManager buddyManager, TransactionTable transactionTable,
RPCManager rpcManager, RegionManager regionManager, Marshaller marshaller,
- CommandsFactory commandsFactory, DataContainer dataContainer, MVCCNodeHelper mvccHelper)
+ CommandsFactory commandsFactory, DataContainer dataContainer, MVCCNodeHelper mvccHelper, BatchContainer batchContainer)
{
this.stateTransferManager = stateTransferManager;
this.cacheLoaderManager = cacheLoaderManager;
@@ -100,6 +102,7 @@
this.dataContainer = dataContainer;
this.commandsFactory = commandsFactory;
this.mvccHelper = mvccHelper;
+ this.batchContainer = batchContainer;
}
@Start
@@ -582,6 +585,20 @@
invoker.invoke(ctx, commandsFactory.buildClearDataCommand(tx, fqn));
}
+ public void startBatch()
+ {
+ if (!configuration.isInvocationBatchingEnabled())
+ throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
+ batchContainer.startBatch();
+ }
+
+ public void endBatch(boolean successful)
+ {
+ if (!configuration.isInvocationBatchingEnabled())
+ throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
+ batchContainer.endBatch(successful);
+ }
+
@SuppressWarnings("unchecked")
public Set<Object> getChildrenNames(Fqn fqn)
{
Modified: core/trunk/src/main/java/org/jboss/cache/transaction/BatchModeTransactionManagerLookup.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/transaction/BatchModeTransactionManagerLookup.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/java/org/jboss/cache/transaction/BatchModeTransactionManagerLookup.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -1,6 +1,9 @@
package org.jboss.cache.transaction;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import javax.transaction.TransactionManager;
@@ -9,10 +12,16 @@
*
* @author Bela Ban Sept 5 2003
* @version $Id$
+ * @deprecated Use batching API on Cache instead.
*/
-public class BatchModeTransactionManagerLookup implements TransactionManagerLookup {
+@Deprecated
+public class BatchModeTransactionManagerLookup implements TransactionManagerLookup
+{
+ private Log log = LogFactory.getLog(BatchModeTransactionManagerLookup.class);
- public TransactionManager getTransactionManager() throws Exception {
+ public TransactionManager getTransactionManager() throws Exception
+ {
+ log.warn("Using a deprecated/unsupported transaction manager!");
return BatchModeTransactionManager.getInstance();
}
}
Modified: core/trunk/src/main/resources/jbosscache-config-3.0.xsd
===================================================================
--- core/trunk/src/main/resources/jbosscache-config-3.0.xsd 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/main/resources/jbosscache-config-3.0.xsd 2008-08-07 16:45:39 UTC (rev 6540)
@@ -15,10 +15,11 @@
<xs:element name="invalidation" type="invalidationType" minOccurs="0" maxOccurs="1"/>
<xs:element name="jmxStatistics" type="jmxStatisticsType" minOccurs="0" maxOccurs="1"/>
<xs:element name="listeners" type="listenersType" minOccurs="0" maxOccurs="1"/>
+ <xs:element name="invocationBatching" type="invocationBatchingType" minOccurs="0" maxOccurs="1"/>
<xs:element name="transport" type="transportType" minOccurs="0" maxOccurs="1"/>
<xs:element name="eviction" type="evictionType" minOccurs="0" maxOccurs="1"/>
<xs:element name="loaders" type="loadersType" minOccurs="0" maxOccurs="1"/>
- <xs:element name="customInterceptors" type="customInterceptorsType" minOccurs="0"/>
+ <xs:element name="customInterceptors" type="customInterceptorsType" minOccurs="0" maxOccurs="1"/>
</xs:all>
</xs:complexType>
</xs:element>
@@ -138,6 +139,10 @@
<xs:attribute name="asyncPoolSize" type="positiveInteger"/>
</xs:complexType>
+ <xs:complexType name="invocationBatchingType">
+ <xs:attribute name="enabled" type="booleanType"/>
+ </xs:complexType>
+
<xs:complexType name="transportType">
<xs:sequence>
<xs:element name="jgroupsConfig" type="xs:anyType" minOccurs="0" maxOccurs="1"/>
Added: core/trunk/src/test/java/org/jboss/cache/api/batch/AbstractBatchTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/api/batch/AbstractBatchTest.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/api/batch/AbstractBatchTest.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -0,0 +1,24 @@
+package org.jboss.cache.api.batch;
+
+import org.jboss.cache.Cache;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+public abstract class AbstractBatchTest
+{
+ protected String getOnDifferentThread(final Cache<String, String> cache, final String fqn, final String key) throws InterruptedException
+ {
+ final AtomicReference<String> ref = new AtomicReference<String>();
+ Thread t = new Thread()
+ {
+ public void run()
+ {
+ ref.set(cache.get(fqn, key));
+ }
+ };
+
+ t.start();
+ t.join();
+ return ref.get();
+ }
+}
Added: core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithTM.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithTM.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithTM.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -0,0 +1,124 @@
+package org.jboss.cache.api.batch;
+
+import org.jboss.cache.Cache;
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.Configuration.CacheMode;
+import org.jboss.cache.config.Configuration.NodeLockingScheme;
+import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
+import org.jboss.cache.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import javax.transaction.TransactionManager;
+
+@Test(groups = {"functional", "transaction"})
+public class BatchWithTM extends AbstractBatchTest
+{
+ public void testBatchWithOngoingTM() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ tm.begin();
+ cache.put("/a/b/c", "k", "v");
+ cache.startBatch();
+ cache.put("/a/b/c", "k2", "v2");
+ tm.commit();
+
+ assert "v".equals(cache.get("/a/b/c", "k"));
+ assert "v2".equals(cache.get("/a/b/c", "k2"));
+
+ cache.endBatch(false); // should be a no op
+ assert "v".equals(cache.get("/a/b/c", "k"));
+ assert "v2".equals(cache.get("/a/b/c", "k2"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchWithoutOngoingTMSuspension() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+ cache.startBatch();
+ cache.put("/a/b/c", "k", "v");
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+ cache.put("/a/b/c", "k2", "v2");
+
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null;
+ assert getOnDifferentThread(cache, "/a/b/c", "k2") == null;
+
+ try
+ {
+ tm.commit(); // should have no effect
+ }
+ catch (Exception e)
+ {
+ // the TM may barf here ... this is OK.
+ }
+
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null;
+ assert getOnDifferentThread(cache, "/a/b/c", "k2") == null;
+
+ cache.endBatch(true); // should be a no op
+
+ assert "v".equals(getOnDifferentThread(cache, "/a/b/c", "k"));
+ assert "v2".equals(getOnDifferentThread(cache, "/a/b/c", "k2"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchRollback() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ cache.startBatch();
+ cache.put("/a/b/c", "k", "v");
+ cache.put("/a/b/c", "k2", "v2");
+
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null;
+ assert getOnDifferentThread(cache, "/a/b/c", "k2") == null;
+
+ cache.endBatch(false);
+
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null;
+ assert getOnDifferentThread(cache, "/a/b/c", "k2") == null;
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ private TransactionManager getTransactionManager(Cache<String, String> c)
+ {
+ return c.getConfiguration().getRuntimeConfig().getTransactionManager();
+ }
+
+ private Cache<String, String> createCache()
+ {
+ CacheFactory<String, String> cf = new DefaultCacheFactory<String, String>();
+ Configuration c = UnitTestCacheConfigurationFactory.createConfiguration(CacheMode.LOCAL); // this should pick up any configured TM for the test
+ c.setNodeLockingScheme(NodeLockingScheme.MVCC);
+ c.setInvocationBatchingEnabled(true);
+ assert c.getTransactionManagerLookupClass() != null : "Should have a transaction manager lookup class attached!!";
+ return cf.createCache(c);
+ }
+}
Added: core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithoutTM.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithoutTM.java (rev 0)
+++ core/trunk/src/test/java/org/jboss/cache/api/batch/BatchWithoutTM.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -0,0 +1,146 @@
+package org.jboss.cache.api.batch;
+
+import org.jboss.cache.Cache;
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.Configuration.NodeLockingScheme;
+import org.jboss.cache.config.ConfigurationException;
+import org.jboss.cache.util.TestingUtil;
+import org.testng.annotations.Test;
+
+@Test(groups = "functional")
+public class BatchWithoutTM extends AbstractBatchTest
+{
+ public void testBatchWithoutCfg()
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(false);
+ try
+ {
+ cache.startBatch();
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good)
+ {
+ // do nothing
+ }
+
+ try
+ {
+ cache.endBatch(true);
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good)
+ {
+ // do nothing
+ }
+
+ try
+ {
+ cache.endBatch(false);
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good)
+ {
+ // do nothing
+ }
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testEndBatchWithoutStartBatch()
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.endBatch(true);
+ cache.endBatch(false);
+ // should not fail.
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testStartBatchIdempotency()
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("/a/b/c", "k", "v");
+ cache.startBatch(); // again
+ cache.put("/a/b/c", "k2", "v2");
+ cache.endBatch(true);
+
+ assert "v".equals(cache.get("/a/b/c", "k"));
+ assert "v2".equals(cache.get("/a/b/c", "k2"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchVisibility() throws InterruptedException
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("/a/b/c", "k", "v");
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null : "Other thread should not see batch update till batch completes!";
+
+ cache.endBatch(true);
+
+ assert "v".equals(getOnDifferentThread(cache, "/a/b/c", "k"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchRollback() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("/a/b/c", "k", "v");
+ cache.put("/a/b/c", "k2", "v2");
+
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null;
+ assert getOnDifferentThread(cache, "/a/b/c", "k2") == null;
+
+ cache.endBatch(false);
+
+ assert getOnDifferentThread(cache, "/a/b/c", "k") == null;
+ assert getOnDifferentThread(cache, "/a/b/c", "k2") == null;
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ private Cache<String, String> createCache(boolean enableBatch)
+ {
+ CacheFactory<String, String> cf = new DefaultCacheFactory<String, String>();
+ Configuration c = new Configuration();
+ c.setNodeLockingScheme(NodeLockingScheme.MVCC);
+ c.setInvocationBatchingEnabled(enableBatch);
+ return cf.createCache(c);
+ }
+}
Modified: core/trunk/src/test/java/org/jboss/cache/config/parsing/XmlConfigurationParserTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/config/parsing/XmlConfigurationParserTest.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/test/java/org/jboss/cache/config/parsing/XmlConfigurationParserTest.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -269,4 +269,9 @@
{
assert config.getListenerAsyncPoolSize() == 5;
}
+
+ public void testInvocationBatching()
+ {
+ assert config.isInvocationBatchingEnabled();
+ }
}
Modified: core/trunk/src/test/java/org/jboss/cache/factories/InterceptorChainFactoryTest.java
===================================================================
--- core/trunk/src/test/java/org/jboss/cache/factories/InterceptorChainFactoryTest.java 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/test/java/org/jboss/cache/factories/InterceptorChainFactoryTest.java 2008-08-07 16:45:39 UTC (rev 6540)
@@ -67,7 +67,29 @@
assertInterceptorLinkage(list);
}
+ public void testBatchingConfig() throws Exception
+ {
+ cache.getConfiguration().setExposeManagementStatistics(false);
+ cache.getConfiguration().setInvocationBatchingEnabled(true);
+ InterceptorChain chain = getInterceptorChainFactory(cache).buildInterceptorChain();
+ List<CommandInterceptor> list = chain.asList();
+ Iterator<CommandInterceptor> interceptors = list.iterator();
+ System.out.println("testBareConfig interceptors are:\n" + list);
+ assertNotNull(list);
+ assertEquals(6, list.size());
+
+ assertEquals(BatchingInterceptor.class, interceptors.next().getClass());
+ assertEquals(InvocationContextInterceptor.class, interceptors.next().getClass());
+ assertEquals(TxInterceptor.class, interceptors.next().getClass());
+ assertEquals(NotificationInterceptor.class, interceptors.next().getClass());
+ assertEquals(PessimisticLockInterceptor.class, interceptors.next().getClass());
+ assertEquals(CallInterceptor.class, interceptors.next().getClass());
+
+ assertInterceptorLinkage(list);
+ }
+
+
public void testMvccConfig() throws Exception
{
cache.getConfiguration().setExposeManagementStatistics(false);
Modified: core/trunk/src/test/resources/configs/parser-test.xml
===================================================================
--- core/trunk/src/test/resources/configs/parser-test.xml 2008-08-07 16:04:06 UTC (rev 6539)
+++ core/trunk/src/test/resources/configs/parser-test.xml 2008-08-07 16:45:39 UTC (rev 6540)
@@ -113,4 +113,5 @@
<!-- the number of threads to use for asynchronous cache listeners - defaults to 1 -->
<listeners asyncPoolSize="5"/>
+ <invocationBatching enabled="true"/>
</jbosscache>
16 years, 5 months
JBoss Cache SVN: r6539 - core/trunk/src/main/java/org/jboss/cache/commands.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-08-07 12:04:06 -0400 (Thu, 07 Aug 2008)
New Revision: 6539
Modified:
core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java
Log:
Deprecated CreateNodeCommand visitors
Modified: core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java 2008-08-07 15:54:03 UTC (rev 6538)
+++ core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java 2008-08-07 16:04:06 UTC (rev 6539)
@@ -1,7 +1,6 @@
package org.jboss.cache.commands;
import org.jboss.cache.commands.legacy.write.CreateNodeCommand;
-import org.jboss.cache.commands.local.BatchBoundaryCommand;
import org.jboss.cache.commands.read.ExistsCommand;
import org.jboss.cache.commands.read.GetChildrenNamesCommand;
import org.jboss.cache.commands.read.GetDataMapCommand;
16 years, 5 months
JBoss Cache SVN: r6538 - in core/trunk/src/main/java/org/jboss/cache: interceptors and 1 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-08-07 11:54:03 -0400 (Thu, 07 Aug 2008)
New Revision: 6538
Modified:
core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java
core/trunk/src/main/java/org/jboss/cache/interceptors/base/PrePostProcessingCommandInterceptor.java
Log:
Deprecated CreateNodeCommand visitors
Modified: core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java 2008-08-07 12:04:30 UTC (rev 6537)
+++ core/trunk/src/main/java/org/jboss/cache/commands/Visitor.java 2008-08-07 15:54:03 UTC (rev 6538)
@@ -1,6 +1,7 @@
package org.jboss.cache.commands;
import org.jboss.cache.commands.legacy.write.CreateNodeCommand;
+import org.jboss.cache.commands.local.BatchBoundaryCommand;
import org.jboss.cache.commands.read.ExistsCommand;
import org.jboss.cache.commands.read.GetChildrenNamesCommand;
import org.jboss.cache.commands.read.GetDataMapCommand;
@@ -242,6 +243,8 @@
* @param command command to visit
* @return response from the visit
* @throws Throwable in the event of problems.
+ * @deprecated in 3.0. Will be removed once optimistic and pessimistic locking is removed.
*/
+ @Deprecated
Object visitCreateNodeCommand(InvocationContext ctx, CreateNodeCommand command) throws Throwable;
}
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java 2008-08-07 12:04:30 UTC (rev 6537)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java 2008-08-07 15:54:03 UTC (rev 6538)
@@ -5,7 +5,6 @@
import org.jboss.cache.InternalNode;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.commands.legacy.write.CreateNodeCommand;
import org.jboss.cache.commands.read.ExistsCommand;
import org.jboss.cache.commands.read.GetChildrenNamesCommand;
import org.jboss.cache.commands.read.GetDataMapCommand;
@@ -265,12 +264,6 @@
}
@Override
- public Object handleCreateNodeCommand(InvocationContext ctx, CreateNodeCommand command) throws Throwable
- {
- throw new UnsupportedOperationException("Unsupported in MVCC!");
- }
-
- @Override
public Object handleRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
{
Object retval = null;
Modified: core/trunk/src/main/java/org/jboss/cache/interceptors/base/PrePostProcessingCommandInterceptor.java
===================================================================
--- core/trunk/src/main/java/org/jboss/cache/interceptors/base/PrePostProcessingCommandInterceptor.java 2008-08-07 12:04:30 UTC (rev 6537)
+++ core/trunk/src/main/java/org/jboss/cache/interceptors/base/PrePostProcessingCommandInterceptor.java 2008-08-07 15:54:03 UTC (rev 6538)
@@ -128,6 +128,10 @@
}
}
+ /**
+ * @deprecated in 3.0. Will be removed when Optimistic and Pessimistic locking is removed.
+ */
+ @Deprecated
protected Object handleCreateNodeCommand(InvocationContext ctx, CreateNodeCommand command) throws Throwable
{
return handleDefault(ctx, command);
16 years, 5 months