Index: src/main/java/org/apache/jackrabbit/core/RepositoryContext.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/RepositoryContext.java	(revision 1159076)
+++ src/main/java/org/apache/jackrabbit/core/RepositoryContext.java	(working copy)
@@ -21,6 +21,7 @@
 import org.apache.jackrabbit.core.fs.FileSystem;
 import org.apache.jackrabbit.core.id.NodeId;
 import org.apache.jackrabbit.core.id.NodeIdFactory;
+import org.apache.jackrabbit.core.jmx.StatManager;
 import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry;
 import org.apache.jackrabbit.core.security.JackrabbitSecurityManager;
 import org.apache.jackrabbit.core.security.authorization.PrivilegeRegistry;
@@ -105,6 +106,11 @@
     private final Timer timer = new Timer(false);
 
     /**
+     * The Statistics manager, handles statistics and jmx support
+     */
+    private StatManager statManager;
+
+    /**
      * Creates a component context for the given repository.
      *
      * @param repository repository instance
@@ -359,4 +365,13 @@
         return nodeIdFactory;
     }
 
+    public StatManager getStatManager() {
+        assert statManager != null;
+        return statManager;
+    }
+
+    public void setStatManager(StatManager statManager) {
+        assert statManager != null;
+        this.statManager = statManager;
+    }
 }
Index: src/main/java/org/apache/jackrabbit/core/jmx/StatManager.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/StatManager.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/StatManager.java	(revision 0)
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx;
+
+import org.apache.jackrabbit.core.jmx.core.CoreStat;
+import org.apache.jackrabbit.core.jmx.core.CoreStatImpl;
+import org.apache.jackrabbit.core.jmx.query.QueryStat;
+import org.apache.jackrabbit.core.jmx.query.QueryStatImpl;
+import org.apache.jackrabbit.core.jmx.registry.JmxRegistry;
+import org.apache.jackrabbit.core.jmx.registry.JmxRegistryImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * StatManager represents a single entry point to the stats objects available.<br>
+ * 
+ * It is disabled by default, and it can be enabled via a system property called
+ * "<code>enableJmxSupport</code>", like:<br>
+ * 
+ * <code>-DenableJmxSupport=true</code>
+ * 
+ */
+public class StatManager {
+
+    private static final Logger log = LoggerFactory
+            .getLogger(StatManager.class);
+
+    private static final Boolean DEFAULT_JMX_SUPPORT = Boolean.valueOf(System
+            .getProperty("enableJmxSupport", "false"));
+
+    private JmxRegistry jmxRegistry;
+
+    private final boolean enableJmxSupport;
+
+    /* STATS */
+    private final QueryStat queryStat = new QueryStatImpl();
+
+    private final CoreStat coreStat = new CoreStatImpl();
+
+    public StatManager(final boolean enableJmxSupport) {
+        this.enableJmxSupport = enableJmxSupport;
+    }
+
+    public StatManager() {
+        this(DEFAULT_JMX_SUPPORT);
+    }
+
+    public void init() {
+        coreStat.setEnabled(false);
+        queryStat.setEnabled(false);
+        if (enableJmxSupport) {
+            enableJxmRegistry();
+        }
+        log.debug("Started StatManager. Jmx support enabled {}.",
+                enableJmxSupport);
+    }
+
+    protected void enableJxmRegistry() {
+        if (jmxRegistry != null) {
+            return;
+        }
+        jmxRegistry = new JmxRegistryImpl(this);
+        jmxRegistry.start();
+    }
+
+    public void stop() {
+        if (jmxRegistry != null) {
+            jmxRegistry.stop();
+        }
+    }
+
+    public CoreStat getCoreStat() {
+        return coreStat;
+    }
+
+    public QueryStat getQueryStat() {
+        return queryStat;
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/JackrabbitBaseMBean.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/JackrabbitBaseMBean.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/JackrabbitBaseMBean.java	(revision 0)
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx;
+
+/**
+ * This should be the base for any MBean Services built for Jackrabbit
+ * 
+ */
+public interface JackrabbitBaseMBean {
+
+    String DOMAIN = "org.apache.jackrabbit";
+
+    /**
+     * If this service is currently registering stats
+     * 
+     * @return <code>true</code> if the service is enabled
+     */
+    boolean isEnabled();
+
+    /**
+     * Enables the service
+     * 
+     */
+    void enable();
+
+    /**
+     * Disables the service
+     * 
+     */
+    void disable();
+
+    /**
+     * clears all data
+     */
+    void reset();
+
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStat.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStat.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStat.java	(revision 0)
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.core;
+
+/**
+ * Statistics on core JCR operations
+ * 
+ */
+public interface CoreStat {
+
+    /** -- SESSION INFO -- **/
+
+    void sessionCreated();
+
+    void sessionLoggedOut();
+
+    long getNumberOfSessions();
+
+    void resetNumberOfSessions();
+
+    /**
+     * @param timeNs
+     *            as given by timeNs = System.nanoTime() - timeNs;
+     */
+    void onSessionOperation(boolean isWrite, long timeNs);
+
+    double getReadOpsPerSecond();
+
+    double getWriteOpsPerSecond();
+
+    void resetNumberOfOperations();
+
+    /**
+     * If this service is currently registering stats
+     * 
+     * @return <code>true</code> if the service is enabled
+     */
+    boolean isEnabled();
+
+    /**
+     * Enables/Disables the service
+     * 
+     * @param enabled
+     */
+    void setEnabled(boolean enabled);
+
+    /**
+     * clears all data
+     */
+    void reset();
+
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatImpl.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatImpl.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatImpl.java	(revision 0)
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.core;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.jackrabbit.core.jmx.util.CachingOpsPerSecondDto;
+
+/**
+ * Default CoreStat impl
+ * 
+ */
+public class CoreStatImpl implements CoreStat {
+
+    /** -- SESSION INFO -- **/
+
+    private final AtomicLong sessions = new AtomicLong(0);
+
+    private boolean enabled = false;
+
+    private final CachingOpsPerSecondDto reads = new CachingOpsPerSecondDto();
+
+    private final CachingOpsPerSecondDto writes = new CachingOpsPerSecondDto();
+
+    public void sessionCreated() {
+        if (!enabled) {
+            return;
+        }
+        sessions.incrementAndGet();
+    }
+
+    public void sessionLoggedOut() {
+        if (!enabled || sessions.get() == 0) {
+            return;
+        }
+        sessions.decrementAndGet();
+    }
+
+    public long getNumberOfSessions() {
+        return sessions.get();
+    }
+
+    public void resetNumberOfSessions() {
+        sessions.set(0);
+    }
+
+    public void onSessionOperation(boolean isWrite, long timeNs) {
+        if (!enabled) {
+            return;
+        }
+        if (isWrite) {
+            writes.onOp(timeNs);
+        } else {
+            reads.onOp(timeNs);
+        }
+    }
+
+    public double getReadOpsPerSecond() {
+        return reads.getOpsPerSecond();
+    }
+
+    public double getWriteOpsPerSecond() {
+        return writes.getOpsPerSecond();
+    }
+
+    public void resetNumberOfOperations() {
+        reads.reset();
+        writes.reset();
+    }
+
+    /** -- GENERAL INFO -- **/
+
+    public boolean isEnabled() {
+        return enabled;
+    }
+
+    public void setEnabled(boolean enabled) {
+        this.enabled = enabled;
+        if (!this.enabled) {
+            reset();
+        }
+    }
+
+    public void reset() {
+        resetNumberOfSessions();
+        resetNumberOfOperations();
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatManager.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatManager.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatManager.java	(revision 0)
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.core;
+
+/**
+ * The CoreStatManagerMBean default implementation
+ * 
+ */
+public class CoreStatManager implements CoreStatManagerMBean {
+
+    private final CoreStat coreStat;
+
+    public CoreStatManager(final CoreStat coreStat) {
+        this.coreStat = coreStat;
+    }
+
+    public long getNumberOfSessions() {
+        return coreStat.getNumberOfSessions();
+    }
+
+    public void resetNumberOfSessions() {
+        this.coreStat.resetNumberOfSessions();
+    }
+
+    public boolean isEnabled() {
+        return this.coreStat.isEnabled();
+    }
+
+    public void reset() {
+        this.coreStat.reset();
+    }
+
+    public double getReadOpsPerSecond() {
+        return this.coreStat.getReadOpsPerSecond();
+    }
+
+    public double getWriteOpsPerSecond() {
+        return this.coreStat.getWriteOpsPerSecond();
+    }
+
+    public void resetNumberOfOperations() {
+        this.coreStat.resetNumberOfOperations();
+
+    }
+
+    public void enable() {
+        this.coreStat.setEnabled(true);
+    }
+
+    public void disable() {
+        this.coreStat.setEnabled(false);
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatManagerMBean.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatManagerMBean.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/core/CoreStatManagerMBean.java	(revision 0)
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.core;
+
+import org.apache.jackrabbit.core.jmx.JackrabbitBaseMBean;
+
+/**
+ * The CoreStatManagerMBean exposes the CoreStat info via JMX
+ * 
+ */
+public interface CoreStatManagerMBean extends JackrabbitBaseMBean {
+
+    String NAME = DOMAIN + ":type=CoreStats";
+
+    long getNumberOfSessions();
+
+    void resetNumberOfSessions();
+
+    double getReadOpsPerSecond();
+
+    double getWriteOpsPerSecond();
+
+    void resetNumberOfOperations();
+
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStat.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStat.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStat.java	(revision 0)
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+/**
+ * Statistics on query operations
+ * 
+ */
+public interface QueryStat {
+
+    void logQuery(final String language, final String statement, long duration);
+
+    /** Slowest Queries */
+
+    QueryStatDto[] getSlowQueries();
+
+    /**
+     * @return how big the <b>Top X</b> queue is
+     */
+    int getSlowQueriesQueueSize();
+
+    /**
+     * Change the <b>Top X</b> queue size
+     * 
+     * @param size
+     *            the new size
+     */
+    void setSlowQueriesQueueSize(int size);
+
+    /**
+     * clears the queue
+     */
+    void clearSlowQueriesQueue();
+
+    double getQueriesPerSecond();
+
+    double getAvgQueryTime();
+
+    /** Generic Stats Stuff */
+
+    /**
+     * If this service is currently registering stats
+     * 
+     * @return <code>true</code> if the service is enabled
+     */
+    boolean isEnabled();
+
+    /**
+     * Enables/Disables the service
+     * 
+     * @param enabled
+     */
+    void setEnabled(boolean enabled);
+
+    /**
+     * clears all data
+     */
+    void reset();
+
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatDto.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatDto.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatDto.java	(revision 0)
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+import java.io.Serializable;
+import java.util.Calendar;
+import java.util.Date;
+
+/**
+ * Object that holds statistical info about a query.
+ * 
+ */
+public class QueryStatDto implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * lazy, computed at call time
+     */
+    private long position;
+
+    /**
+     * the time that the query was created
+     */
+    private final Date creationTime;
+
+    /**
+     * run duration
+     */
+    private final long duration;
+
+    /**
+     * query language
+     */
+    private final String language;
+
+    /**
+     * query statement
+     */
+    private final String statement;
+
+    public QueryStatDto(final String language, final String statement,
+            long duration) {
+        this.duration = duration;
+        this.language = language;
+        this.statement = statement;
+
+        Calendar c = Calendar.getInstance();
+        c.setTimeInMillis(System.currentTimeMillis() - duration);
+        this.creationTime = c.getTime();
+    }
+
+    public long getDuration() {
+        return duration;
+    }
+
+    public String getLanguage() {
+        return language;
+    }
+
+    public String getStatement() {
+        return statement;
+    }
+
+    public String getCreationTime() {
+        return creationTime.toString();
+    }
+
+    public long getPosition() {
+        return position;
+    }
+
+    public void setPosition(long position) {
+        this.position = position;
+    }
+
+    @Override
+    public String toString() {
+        return "QueryStat [creationTime=" + creationTime + ", duration="
+                + duration + ", language=" + language + ", statement="
+                + statement + "]";
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatDtoComparator.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatDtoComparator.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatDtoComparator.java	(revision 0)
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+import java.util.Comparator;
+
+/**
+ * QueryStatDto comparator by duration
+ * 
+ */
+public class QueryStatDtoComparator implements Comparator<QueryStatDto> {
+    public int compare(QueryStatDto o1, QueryStatDto o2) {
+        return new Long(o1.getDuration()).compareTo(o2.getDuration());
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatImpl.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatImpl.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatImpl.java	(revision 0)
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+import java.util.Comparator;
+import java.util.PriorityQueue;
+
+import org.apache.jackrabbit.core.jmx.util.CachingOpsPerSecondDto;
+
+/**
+ * Default {@link QueryStat} implementation
+ * 
+ */
+public class QueryStatImpl implements QueryStat {
+
+    private final static Comparator<QueryStatDto> comparator = new QueryStatDtoComparator();
+
+    private int queueSize = 15;
+
+    private PriorityQueue<QueryStatDto> queries = new PriorityQueue<QueryStatDto>(
+            queueSize + 1, comparator);
+
+    private CachingOpsPerSecondDto qps = new CachingOpsPerSecondDto();
+
+    private boolean enabled = false;
+
+    public QueryStatImpl() {
+    }
+
+    public int getSlowQueriesQueueSize() {
+        return queueSize;
+    }
+
+    public synchronized void setSlowQueriesQueueSize(int size) {
+        this.queueSize = size;
+        this.queries = new PriorityQueue<QueryStatDto>(this.queueSize + 1,
+                comparator);
+    }
+
+    public boolean isEnabled() {
+        return enabled;
+    }
+
+    public void setEnabled(boolean enabled) {
+        this.enabled = enabled;
+        this.queries = new PriorityQueue<QueryStatDto>(this.queueSize + 1,
+                comparator);
+    }
+
+    public synchronized void logQuery(final String language,
+            final String statement, long duration) {
+        if (!enabled) {
+            return;
+        }
+        queries.add(new QueryStatDto(language, statement, duration));
+        if (queries.size() > queueSize) {
+            queries.remove();
+        }
+        qps.onOp(duration * 1000);
+    }
+
+    public void clearSlowQueriesQueue() {
+        this.queries.clear();
+    }
+
+    public void reset() {
+        clearSlowQueriesQueue();
+    }
+
+    public QueryStatDto[] getSlowQueries() {
+        return queries.toArray(new QueryStatDto[queries.size()]);
+    }
+
+    public double getQueriesPerSecond() {
+        return qps.getOpsPerSecond();
+    }
+
+    public double getAvgQueryTime() {
+        return qps.getOpAvgTime();
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatManager.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatManager.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatManager.java	(revision 0)
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+
+import javax.management.openmbean.CompositeDataSupport;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.OpenDataException;
+import javax.management.openmbean.OpenType;
+import javax.management.openmbean.SimpleType;
+import javax.management.openmbean.TabularData;
+import javax.management.openmbean.TabularDataSupport;
+import javax.management.openmbean.TabularType;
+
+/**
+ * The QueryStatManagerMBean default implementation
+ * 
+ */
+public class QueryStatManager implements QueryStatManagerMBean {
+
+    private final QueryStat queryStat;
+
+    private final static Comparator<QueryStatDto> comparatorRev = Collections
+            .reverseOrder(new QueryStatDtoComparator());
+
+    public QueryStatManager(final QueryStat queryStat) {
+        this.queryStat = queryStat;
+    }
+
+    public boolean isEnabled() {
+        return this.queryStat.isEnabled();
+    }
+
+    public void enable() {
+        this.queryStat.setEnabled(true);
+    }
+
+    public void disable() {
+        this.queryStat.setEnabled(false);
+    }
+
+    public void reset() {
+        this.queryStat.reset();
+    }
+
+    public int getQueueSize() {
+        return queryStat.getSlowQueriesQueueSize();
+    }
+
+    public void setQueueSize(int size) {
+        this.queryStat.setSlowQueriesQueueSize(size);
+    }
+
+    public void clearQueue() {
+        this.queryStat.clearSlowQueriesQueue();
+    }
+
+    public QueryStatDto[] getTopQueries() {
+        QueryStatDto[] top = this.queryStat.getSlowQueries();
+        Arrays.sort(top, comparatorRev);
+        for (int i = 0; i < top.length; i++) {
+            top[i].setPosition(i + 1);
+        }
+        return top;
+    }
+
+    public TabularData getQueries() {
+        TabularDataSupport tds = null;
+        try {
+            CompositeType ct = QueryStatCompositeTypeFactory.getCompositeType();
+
+            TabularType tt = new TabularType(QueryStatDto.class.getName(),
+                    "Query History", ct, QueryStatCompositeTypeFactory.index);
+            tds = new TabularDataSupport(tt);
+
+            for (QueryStatDto q : getTopQueries()) {
+                tds.put(new CompositeDataSupport(ct,
+                        QueryStatCompositeTypeFactory.names,
+                        QueryStatCompositeTypeFactory.getValues(q)));
+            }
+            return tds;
+        } catch (Exception e) {
+            e.printStackTrace();
+            return null;
+        }
+    }
+
+    private static class QueryStatCompositeTypeFactory {
+
+        private final static String[] index = { "position" };
+
+        private final static String[] names = { "position", "duration",
+                "language", "statement", "creationTime" };
+
+        private final static String[] descriptions = { "position", "duration",
+                "language", "statement", "creationTime" };
+
+        private final static OpenType[] types = { SimpleType.LONG,
+                SimpleType.LONG, SimpleType.STRING, SimpleType.STRING,
+                SimpleType.STRING };
+
+        public static CompositeType getCompositeType() throws OpenDataException {
+            return new CompositeType(QueryStat.class.getName(),
+                    QueryStat.class.getName(), names, descriptions, types);
+        }
+
+        public static Object[] getValues(QueryStatDto q) {
+            return new Object[] { q.getPosition(), q.getDuration(),
+                    q.getLanguage(), q.getStatement(), q.getCreationTime() };
+        }
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatManagerMBean.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatManagerMBean.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/query/QueryStatManagerMBean.java	(revision 0)
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+import javax.management.openmbean.TabularData;
+
+import org.apache.jackrabbit.core.jmx.JackrabbitBaseMBean;
+
+/**
+ * JMX Bindings for {@link QueryStat}.
+ * 
+ */
+public interface QueryStatManagerMBean extends JackrabbitBaseMBean {
+
+    String NAME = DOMAIN + ":type=QueryStats";
+
+    TabularData getQueries();
+
+    /**
+     * @return how big the <b>Top X</b> queue is
+     */
+    int getQueueSize();
+
+    /**
+     * Change the <b>Top X</b> queue size
+     * 
+     * @param size
+     *            the new size
+     */
+    void setQueueSize(int size);
+
+    /**
+     * clears the queue
+     */
+    void clearQueue();
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/util/CachingOpsPerSecondDto.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/util/CachingOpsPerSecondDto.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/util/CachingOpsPerSecondDto.java	(revision 0)
@@ -0,0 +1,152 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.util;
+
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+/**
+ * Statistical data structure, use to compute stats on operations
+ * 
+ */
+public class CachingOpsPerSecondDto {
+
+    // @ 1 min
+    public static long DEFAULT_UPDATE_FREQ_MS = 1000 * 60 * 1;
+
+    private final long updateFreqMs;
+
+    private final ReadWriteLock rwl = new ReentrantReadWriteLock();
+    private final Lock r = rwl.readLock();
+    private final Lock w = rwl.writeLock();
+
+    // intermediary values
+
+    private long lastUpdate = System.currentTimeMillis();
+
+    private long startMs = System.currentTimeMillis();
+
+    private long operations = 0;
+
+    private long totalTimeNs = 0;
+
+    // cached stats
+
+    private double opsPerSecond = 0;
+
+    private double opAvgTime = 0;
+
+    public CachingOpsPerSecondDto(long updateFreqMs) {
+        this.updateFreqMs = updateFreqMs;
+    }
+
+    public CachingOpsPerSecondDto() {
+        this(DEFAULT_UPDATE_FREQ_MS);
+    }
+
+    public void onOp(long timeNs) {
+        w.lock();
+        try {
+            final long localStart = System.currentTimeMillis() - timeNs / 1000;
+            if (localStart < startMs) {
+                startMs = localStart;
+            }
+            operations++;
+            totalTimeNs += timeNs;
+        } finally {
+            w.unlock();
+        }
+    }
+
+    public double getOpsPerSecond() {
+        checkUpdate(false);
+        return opsPerSecond;
+    }
+
+    public double getOpAvgTime() {
+        checkUpdate(false);
+        return opAvgTime;
+    }
+
+    private void checkUpdate(boolean forceUpdate) {
+        r.lock();
+        final long now = System.currentTimeMillis();
+        try {
+            if (!forceUpdate && now - lastUpdate < updateFreqMs) {
+                return;
+            }
+        } finally {
+            r.unlock();
+        }
+        w.lock();
+        try {
+            if (!forceUpdate && now - lastUpdate < updateFreqMs) {
+                return;
+            }
+            update(now);
+        } finally {
+            w.unlock();
+        }
+    }
+
+    private final static BigDecimal thousand = BigDecimal.valueOf(1000);
+
+    private final static MathContext DEFAULT_CONTEXT = new MathContext(3);
+
+    private void update(long now) {
+        if (operations == 0) {
+            opsPerSecond = 0;
+            opAvgTime = 0;
+            return;
+        }
+        long durationMs = now - startMs;
+        if (durationMs == 0) {
+            durationMs = 1000;
+        }
+        opsPerSecond = BigDecimal.valueOf(operations).multiply(thousand)
+                .divide(BigDecimal.valueOf(durationMs), DEFAULT_CONTEXT)
+                .doubleValue();
+        opAvgTime = BigDecimal.valueOf(totalTimeNs)
+                .divide(BigDecimal.valueOf(operations), DEFAULT_CONTEXT)
+                .doubleValue();
+        // reset if needed
+        if (operations > Long.MAX_VALUE - 5000) {
+            reset();
+        }
+    }
+
+    public void reset() {
+        w.lock();
+        try {
+            opsPerSecond = 0;
+            opAvgTime = 0;
+            lastUpdate = System.currentTimeMillis();
+            operations = 0;
+            startMs = lastUpdate;
+            totalTimeNs = 0;
+        } finally {
+            w.unlock();
+        }
+    }
+
+    protected void refresh() {
+        checkUpdate(true);
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistry.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistry.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistry.java	(revision 0)
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.registry;
+
+import javax.management.ObjectName;
+
+import org.apache.jackrabbit.core.jmx.JackrabbitBaseMBean;
+
+/**
+ * JMX Mbean dynamic registration service
+ * 
+ */
+public interface JmxRegistry {
+
+    /**
+     * starts the service
+     */
+    void start();
+
+    /**
+     * stops the service
+     */
+    void stop();
+
+    /**
+     * Registers a new MBEan under the given name
+     * 
+     * @param bean
+     *            to be registered
+     * @param name
+     * @throws Exception
+     */
+    void register(JackrabbitBaseMBean bean, ObjectName name) throws Exception;
+
+    /**
+     * Unregisters a bean
+     * 
+     * @param name
+     * @throws Exception
+     */
+    void unregister(ObjectName name) throws Exception;
+
+    void enableCoreStatJmx();
+
+    void enableQueryStatJmx();
+
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryImpl.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryImpl.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryImpl.java	(revision 0)
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.registry;
+
+import java.lang.management.ManagementFactory;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.apache.jackrabbit.core.jmx.JackrabbitBaseMBean;
+import org.apache.jackrabbit.core.jmx.StatManager;
+import org.apache.jackrabbit.core.jmx.core.CoreStatManager;
+import org.apache.jackrabbit.core.jmx.core.CoreStatManagerMBean;
+import org.apache.jackrabbit.core.jmx.query.QueryStatManager;
+import org.apache.jackrabbit.core.jmx.query.QueryStatManagerMBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * JmxRegistry default implementation
+ * 
+ */
+public class JmxRegistryImpl implements JmxRegistry {
+
+    private static Logger log = LoggerFactory.getLogger(JmxRegistryImpl.class);
+
+    /* JMX */
+    private MBeanServer server;
+
+    private final List<ObjectName> registry = new ArrayList<ObjectName>();
+
+    /* Stats */
+    private final StatManager statManager;
+
+    public JmxRegistryImpl(final StatManager statManager) {
+        this.statManager = statManager;
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.apache.jackrabbit.core.jmx.JmxRegistry#start()
+     */
+    public void start() {
+        server = ManagementFactory.getPlatformMBeanServer();
+        enableRegistry();
+        log.debug("Started JMX Registry.");
+    }
+
+    public void enableRegistry() {
+        if (server == null) {
+            return;
+        }
+        try {
+            register(new JmxRegistryManager(this), new ObjectName(
+                    JmxRegistryManagerMBean.NAME));
+            log.debug("JMX Registry - registered DynamicRegistry.");
+        } catch (Exception e) {
+            log.error("JMX Registry - Unable to register DynamicRegistry.", e);
+        }
+    }
+
+    public void enableCoreStatJmx() {
+        if (server == null) {
+            return;
+        }
+        try {
+            register(new CoreStatManager(statManager.getCoreStat()),
+                    new ObjectName(CoreStatManagerMBean.NAME));
+            log.debug("JMX Registry - registered CoreStats.");
+        } catch (Exception e) {
+            log.error("JMX Registry - Unable to register CoreStats.", e);
+        }
+    }
+
+    public void enableQueryStatJmx() {
+        if (server == null) {
+            return;
+        }
+        try {
+            register(new QueryStatManager(statManager.getQueryStat()),
+                    new ObjectName(QueryStatManagerMBean.NAME));
+            log.debug("JMX Registry - registered QueryStats.");
+        } catch (Exception e) {
+            log.error("JMX Registry - Unable to register CoreStats.", e);
+        }
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see org.apache.jackrabbit.core.jmx.JmxRegistry#stop()
+     */
+    public void stop() {
+        if (server == null) {
+            return;
+        }
+
+        List<ObjectName> registryCopy = new ArrayList<ObjectName>(registry);
+        for (ObjectName o : registryCopy) {
+            try {
+                unregister(o);
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        registry.clear();
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see
+     * org.apache.jackrabbit.core.jmx.JmxRegistry#register(org.apache.jackrabbit
+     * .core.jmx.JackrabbitMBean, javax.management.ObjectName)
+     */
+    public void register(JackrabbitBaseMBean bean, ObjectName name)
+            throws Exception {
+        if (server == null || server.isRegistered(name)) {
+            return;
+        }
+        this.server.registerMBean(bean, name);
+        this.registry.add(name);
+    }
+
+    /*
+     * (non-Javadoc)
+     * 
+     * @see
+     * org.apache.jackrabbit.core.jmx.JmxRegistry#unregister(javax.management
+     * .ObjectName)
+     */
+    public void unregister(ObjectName name) throws Exception {
+        if (server == null || !server.isRegistered(name)) {
+            return;
+        }
+        registry.remove(name);
+        server.unregisterMBean(name);
+    }
+
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryManager.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryManager.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryManager.java	(revision 0)
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.registry;
+
+/**
+ * JmxRegistryManagerMBean default implementation
+ * 
+ */
+public class JmxRegistryManager implements JmxRegistryManagerMBean {
+
+    private final JmxRegistry jmxRegistry;
+
+    public JmxRegistryManager(final JmxRegistry jmxRegistry) {
+        this.jmxRegistry = jmxRegistry;
+    }
+
+    public void enableCoreStatJmx() {
+        jmxRegistry.enableCoreStatJmx();
+    }
+
+    public void enableQueryStatJmx() {
+        jmxRegistry.enableQueryStatJmx();
+    }
+
+    public boolean isEnabled() {
+        return true;
+    }
+
+    public void reset() {
+        throw new UnsupportedOperationException();
+    }
+
+    public void enable() {
+        throw new UnsupportedOperationException();
+    }
+
+    public void disable() {
+        throw new UnsupportedOperationException();
+    }
+}
Index: src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryManagerMBean.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryManagerMBean.java	(revision 0)
+++ src/main/java/org/apache/jackrabbit/core/jmx/registry/JmxRegistryManagerMBean.java	(revision 0)
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.registry;
+
+import org.apache.jackrabbit.core.jmx.JackrabbitBaseMBean;
+
+/**
+ * JmxRegistry JMX MBean public operations
+ * 
+ */
+public interface JmxRegistryManagerMBean extends JackrabbitBaseMBean {
+
+    String NAME = DOMAIN + ":type=DynamicRegistry";
+
+    void enableCoreStatJmx();
+
+    void enableQueryStatJmx();
+
+}
Index: src/main/java/org/apache/jackrabbit/core/RepositoryImpl.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/RepositoryImpl.java	(revision 1159076)
+++ src/main/java/org/apache/jackrabbit/core/RepositoryImpl.java	(working copy)
@@ -82,6 +82,7 @@
 import org.apache.jackrabbit.core.fs.FileSystemResource;
 import org.apache.jackrabbit.core.id.NodeId;
 import org.apache.jackrabbit.core.id.NodeIdFactory;
+import org.apache.jackrabbit.core.jmx.StatManager;
 import org.apache.jackrabbit.core.lock.LockManager;
 import org.apache.jackrabbit.core.lock.LockManagerImpl;
 import org.apache.jackrabbit.core.nodetype.NodeTypeRegistry;
@@ -232,6 +233,11 @@
     private final CacheManager cacheMgr = new CacheManager();
 
     /**
+     * The Statistics manager, handles statistics and jmx support
+     */
+    private final StatManager statManager = new StatManager();
+    
+    /**
      * Chanel for posting create workspace messages.
      */
     private WorkspaceEventChannel createWorkspaceEventChannel;
@@ -355,6 +361,9 @@
             // initialize system search manager
             getSystemSearchManager(repConfig.getDefaultWorkspaceName());
 
+            //this has to be live before initSecurityManager(), to be able to track all the queries
+            initStatManager();
+
             // Initialise the security manager;
             initSecurityManager();
 
@@ -461,6 +470,10 @@
         return cacheMgr;
     }
 
+    public StatManager getStatManager() {
+        return statManager;
+    }
+
     /**
      * Creates the {@link org.apache.jackrabbit.core.security.JackrabbitSecurityManager SecurityManager}
      * of this <code>Repository</code> and adds it to the repository context.
@@ -1003,6 +1016,7 @@
             session.addListener(this);
             activeSessions.put(session, session);
         }
+        statManager.getCoreStat().sessionCreated();
     }
 
     /**
@@ -1192,6 +1206,8 @@
 
         context.getTimer().cancel();
 
+        statManager.stop();
+
         log.info("Repository has been shutdown");
     }
 
@@ -1452,6 +1468,11 @@
         return new GarbageCollector(context.getDataStore(), ipmList, sessions);
     }
 
+    protected void initStatManager() {
+        this.statManager.init();
+        this.context.setStatManager(statManager);
+    }
+
     //-----------------------------------------------------------< Repository >
     /**
      * {@inheritDoc}
@@ -1587,6 +1608,7 @@
             // remove session from active sessions
             activeSessions.remove(session);
         }
+        statManager.getCoreStat().sessionLoggedOut();
     }
 
     //------------------------------------------< overridable factory methods >
Index: src/main/java/org/apache/jackrabbit/core/session/SessionState.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/session/SessionState.java	(revision 1159076)
+++ src/main/java/org/apache/jackrabbit/core/session/SessionState.java	(working copy)
@@ -23,6 +23,7 @@
 import javax.jcr.Session;
 
 import org.apache.jackrabbit.core.WorkspaceManager;
+import org.apache.jackrabbit.core.jmx.core.CoreStat;
 import org.apache.jackrabbit.core.observation.ObservationDispatcher;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -180,14 +181,16 @@
             }
 
             try {
+                final CoreStat coreStat = context.getRepositoryContext().getStatManager().getCoreStat();
                 // Perform the actual operation, optionally with debug logs
-                if (log.isDebugEnabled()) {
+                if (log.isDebugEnabled() || coreStat.isEnabled()) {
                     log.debug("Performing {}", operation);
                     long start = System.nanoTime();
                     try {
                         return operation.perform(context);
                     } finally {
                         long time = System.nanoTime() - start;
+                        coreStat.onSessionOperation(isWriteOperation, time);
                         if (time > NS_PER_MS) {
                             log.debug("Performed {} in {}ms",
                                     operation, time / NS_PER_MS);
Index: src/main/java/org/apache/jackrabbit/core/query/QueryImpl.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/query/QueryImpl.java	(revision 1159076)
+++ src/main/java/org/apache/jackrabbit/core/query/QueryImpl.java	(working copy)
@@ -20,8 +20,6 @@
 import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_STATEMENT;
 import static org.apache.jackrabbit.spi.commons.name.NameConstants.NT_QUERY;
 
-import java.text.NumberFormat;
-
 import javax.jcr.ItemExistsException;
 import javax.jcr.ItemNotFoundException;
 import javax.jcr.Node;
@@ -35,6 +33,7 @@
 import javax.jcr.query.QueryResult;
 import javax.jcr.version.VersionException;
 
+import org.apache.jackrabbit.core.jmx.query.QueryStat;
 import org.apache.jackrabbit.core.session.SessionContext;
 import org.apache.jackrabbit.core.session.SessionOperation;
 import org.apache.jackrabbit.spi.Path;
@@ -135,14 +134,13 @@
                         return "query.execute(" + statement + ")";
                     }
                 });
-        
-        if (log.isDebugEnabled()) {
+        final QueryStat queryStat = sessionContext.getRepositoryContext()
+                .getStatManager().getQueryStat();
+        if (queryStat.isEnabled() || log.isDebugEnabled()) {
             time = System.currentTimeMillis() - time;
-            NumberFormat format = NumberFormat.getNumberInstance();
-            format.setMinimumFractionDigits(2);
-            format.setMaximumFractionDigits(2);
-            String seconds = format.format((double) time / 1000);
-            log.debug("executed in " + seconds + " s. (" + statement + ")");
+            sessionContext.getRepositoryContext().getStatManager()
+                    .getQueryStat().logQuery(language, statement, time);
+            log.debug("executed in {} ms. ({})", time, statement);
         }
         return result;
     }
Index: src/main/java/org/apache/jackrabbit/core/query/QueryObjectModelImpl.java
===================================================================
--- src/main/java/org/apache/jackrabbit/core/query/QueryObjectModelImpl.java	(revision 1159076)
+++ src/main/java/org/apache/jackrabbit/core/query/QueryObjectModelImpl.java	(working copy)
@@ -16,7 +16,6 @@
  */
 package org.apache.jackrabbit.core.query;
 
-import java.text.NumberFormat;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -32,6 +31,7 @@
 import javax.jcr.query.qom.Source;
 
 import org.apache.jackrabbit.commons.query.QueryObjectModelBuilderRegistry;
+import org.apache.jackrabbit.core.jmx.query.QueryStat;
 import org.apache.jackrabbit.core.query.lucene.LuceneQueryFactory;
 import org.apache.jackrabbit.core.query.lucene.SearchIndex;
 import org.apache.jackrabbit.core.query.lucene.join.QueryEngine;
@@ -122,13 +122,12 @@
         long time = System.currentTimeMillis();
         QueryResult qr = engine.execute(getColumns(), getSource(),
                 getConstraint(), getOrderings(), offset, limit);
-        if (log.isDebugEnabled()) {
+        final QueryStat queryStat = sessionContext.getRepositoryContext()
+                .getStatManager().getQueryStat();
+        if (queryStat.isEnabled() || log.isDebugEnabled()) {
             time = System.currentTimeMillis() - time;
-            NumberFormat format = NumberFormat.getNumberInstance();
-            format.setMinimumFractionDigits(2);
-            format.setMaximumFractionDigits(2);
-            String seconds = format.format((double) time / 1000);
-            log.debug("executed in " + seconds + " s. (" + statement + ")");
+            queryStat.logQuery(language, statement, time);
+            log.debug("executed in {} ms. ({})", time, statement);
         }
         return qr;
     }
Index: src/test/java/org/apache/jackrabbit/core/jmx/util/CachingOpsPerSecondDtoTest.java
===================================================================
--- src/test/java/org/apache/jackrabbit/core/jmx/util/CachingOpsPerSecondDtoTest.java	(revision 0)
+++ src/test/java/org/apache/jackrabbit/core/jmx/util/CachingOpsPerSecondDtoTest.java	(revision 0)
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.util;
+
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.math.RoundingMode;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.jackrabbit.test.JUnitTest;
+
+public class CachingOpsPerSecondDtoTest extends JUnitTest {
+
+    private final CachingOpsPerSecondDto test = new CachingOpsPerSecondDto(
+            1000 * 10000);
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        test.reset();
+    }
+
+    public void testSimple() throws Exception {
+
+        long t = System.currentTimeMillis();
+        test.reset();
+        test.onOp(10);
+        test.onOp(1);
+        TimeUnit.MILLISECONDS.sleep(1300);
+        test.onOp(2);
+        long d_min = System.currentTimeMillis() - t;
+        test.refresh();
+        long d_max = System.currentTimeMillis() - t;
+
+        // 3 ops in ~ 1.3 seconds = 2.3 ops / sec
+        double expected_min = BigDecimal.valueOf(3 * 1000)
+                .divide(BigDecimal.valueOf(d_min), new MathContext(3))
+                .round(new MathContext(2, RoundingMode.DOWN)).doubleValue();
+        double expected_max = BigDecimal.valueOf(3 * 1000)
+                .divide(BigDecimal.valueOf(d_max), new MathContext(3))
+                .add(new BigDecimal(0.001))
+                .round(new MathContext(2, RoundingMode.UP)).doubleValue();
+        double opsPerSecond = test.getOpsPerSecond();
+
+        assertTrue(opsPerSecond + "?" + expected_min,
+                opsPerSecond >= expected_min);
+        assertTrue(opsPerSecond + "?" + expected_max,
+                opsPerSecond <= expected_max);
+        assertEquals(4.33, test.getOpAvgTime());
+
+    }
+
+    public void testMT() throws Exception {
+        int threads = 20;
+        int ops = 60 * threads;
+
+        final Random r = new Random();
+        test.reset();
+        long t = System.currentTimeMillis();
+        int aggDuration = 0;
+        ExecutorService executor = Executors.newFixedThreadPool(threads);
+        List<Future<Void>> futures = new ArrayList<Future<Void>>();
+        for (int i = 0; i < ops; i++) {
+            int duration = 35 + r.nextInt(10);
+            boolean shouldRefresh = i % 10 == 0;
+            futures.add(executor.submit(newCallable(test, duration, 75,
+                    shouldRefresh)));
+            aggDuration += duration;
+        }
+        executor.shutdown();
+        for (Future<Void> f : futures) {
+            f.get();
+        }
+
+        long d_min = System.currentTimeMillis() - t;
+        test.refresh();
+        long d_max = System.currentTimeMillis() - t;
+
+        double expected_min = BigDecimal.valueOf(ops * 1000)
+                .divide(BigDecimal.valueOf(d_min), new MathContext(3))
+                .round(new MathContext(2, RoundingMode.DOWN)).doubleValue();
+        double expected_max = BigDecimal.valueOf(ops * 1000)
+                .divide(BigDecimal.valueOf(d_max), new MathContext(3))
+                .add(new BigDecimal(0.001))
+                .round(new MathContext(2, RoundingMode.UP)).doubleValue();
+        double opsPerSecond = test.getOpsPerSecond();
+
+        assertTrue(opsPerSecond + "?" + expected_min,
+                opsPerSecond >= expected_min);
+        assertTrue(opsPerSecond + "?" + expected_max,
+                opsPerSecond <= expected_max);
+
+        double expectedAvg = BigDecimal
+                .valueOf(aggDuration)
+                .divide(BigDecimal.valueOf(ops),
+                        new MathContext(2, RoundingMode.DOWN)).doubleValue();
+        assertEquals(expectedAvg, BigDecimal.valueOf(test.getOpAvgTime())
+                .round(new MathContext(2, RoundingMode.DOWN)).doubleValue());
+    }
+
+    private Callable<Void> newCallable(final CachingOpsPerSecondDto test,
+            final int duration, final long sleep, final boolean shouldRefresh) {
+        return new Callable<Void>() {
+
+            public Void call() throws Exception {
+                test.onOp(duration);
+                TimeUnit.MILLISECONDS.sleep(sleep);
+                if (shouldRefresh) {
+                    test.refresh();
+                }
+                return null;
+            }
+        };
+    }
+}
Index: src/test/java/org/apache/jackrabbit/core/jmx/TestAll.java
===================================================================
--- src/test/java/org/apache/jackrabbit/core/jmx/TestAll.java	(revision 0)
+++ src/test/java/org/apache/jackrabbit/core/jmx/TestAll.java	(revision 0)
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import org.apache.jackrabbit.core.jmx.core.CoreStatSessionTest;
+import org.apache.jackrabbit.core.jmx.query.QueryStatManagerTest;
+import org.apache.jackrabbit.core.jmx.registry.JmxSupportTest;
+import org.apache.jackrabbit.core.jmx.util.CachingOpsPerSecondDtoTest;
+
+/**
+ * TestSuite for all Stats tests.
+ */
+public class TestAll extends TestCase {
+
+    /**
+     * Returns a <code>Test</code> suite that executes all tests inside this
+     * package.
+     * 
+     */
+    public static Test suite() {
+        TestSuite suite = new TestSuite();
+
+        suite.addTestSuite(JmxSupportTest.class);
+        suite.addTestSuite(CoreStatSessionTest.class);
+        suite.addTestSuite(QueryStatManagerTest.class);
+        suite.addTestSuite(CachingOpsPerSecondDtoTest.class);
+
+        return suite;
+    }
+}
Index: src/test/java/org/apache/jackrabbit/core/jmx/AbstractStatTest.java
===================================================================
--- src/test/java/org/apache/jackrabbit/core/jmx/AbstractStatTest.java	(revision 0)
+++ src/test/java/org/apache/jackrabbit/core/jmx/AbstractStatTest.java	(revision 0)
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx;
+
+import org.apache.jackrabbit.core.RepositoryImpl;
+import org.apache.jackrabbit.test.AbstractJCRTest;
+
+/**
+ * Used as a base class for Statistics related tests.
+ */
+public abstract class AbstractStatTest extends AbstractJCRTest {
+
+    protected StatManager statManager;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        RepositoryImpl r = (RepositoryImpl) superuser.getRepository();
+        statManager = r.getStatManager();
+    }
+
+    protected void enableJxmRegistry() {
+        statManager.enableJxmRegistry();
+    }
+}
Index: src/test/java/org/apache/jackrabbit/core/jmx/core/CoreStatSessionTest.java
===================================================================
--- src/test/java/org/apache/jackrabbit/core/jmx/core/CoreStatSessionTest.java	(revision 0)
+++ src/test/java/org/apache/jackrabbit/core/jmx/core/CoreStatSessionTest.java	(revision 0)
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.core;
+
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+
+import org.apache.jackrabbit.core.jmx.AbstractStatTest;
+
+/**
+ * CoreStats tests.
+ */
+public class CoreStatSessionTest extends AbstractStatTest {
+
+    // TODO add test for number of operations executed
+
+    private CoreStat cs;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        cs = statManager.getCoreStat();
+        cs.resetNumberOfSessions();
+    }
+
+    public void testNumberOfSessions1() throws Exception {
+
+        cs.setEnabled(true);
+        assertEquals(0, cs.getNumberOfSessions());
+
+        Session s = superuser.impersonate(new SimpleCredentials("anonymous", ""
+                .toCharArray()));
+        assertNotNull(s);
+        assertEquals(1, cs.getNumberOfSessions());
+
+        s.logout();
+        assertEquals(0, cs.getNumberOfSessions());
+    }
+
+    public void testNumberOfSessions2() throws Exception {
+
+        cs.setEnabled(false);
+        assertEquals(0, cs.getNumberOfSessions());
+
+        Session s = superuser.impersonate(new SimpleCredentials("anonymous", ""
+                .toCharArray()));
+        assertNotNull(s);
+        assertEquals(0, cs.getNumberOfSessions());
+
+        s.logout();
+        assertEquals(0, cs.getNumberOfSessions());
+    }
+
+    public void testNumberOfSessions3() throws Exception {
+
+        cs.setEnabled(true);
+        assertEquals(0, cs.getNumberOfSessions());
+
+        Session s = superuser.impersonate(new SimpleCredentials("anonymous", ""
+                .toCharArray()));
+        assertNotNull(s);
+        assertEquals(1, cs.getNumberOfSessions());
+
+        cs.resetNumberOfSessions();
+        assertEquals(0, cs.getNumberOfSessions());
+
+        s.logout();
+        assertEquals(0, cs.getNumberOfSessions());
+    }
+}
Index: src/test/java/org/apache/jackrabbit/core/jmx/query/QueryStatManagerTest.java
===================================================================
--- src/test/java/org/apache/jackrabbit/core/jmx/query/QueryStatManagerTest.java	(revision 0)
+++ src/test/java/org/apache/jackrabbit/core/jmx/query/QueryStatManagerTest.java	(revision 0)
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.query;
+
+import javax.jcr.query.Query;
+
+import org.apache.jackrabbit.core.jmx.AbstractStatTest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * QueryStat tests.
+ */
+public class QueryStatManagerTest extends AbstractStatTest {
+
+    private static Logger log = LoggerFactory
+            .getLogger(QueryStatManagerTest.class);
+
+    private QueryStat qs;
+
+    protected void setUp() throws Exception {
+        super.setUp();
+        qs = statManager.getQueryStat();
+        qs.reset();
+    }
+
+    public void testLogDuration() throws Exception {
+        int queueSize = 15;
+        int runTimes = 50;
+
+        qs.setSlowQueriesQueueSize(queueSize);
+        qs.setEnabled(false);
+
+        // just to warm up the cache
+        double initial = doStatTest(runTimes);
+
+        qs.setEnabled(false);
+        double off = doStatTest(runTimes);
+
+        qs.setEnabled(true);
+        double on = doStatTest(runTimes);
+
+        log.info("Logging times: initial=" + initial
+                + ", without QueryStatManager = " + off
+                + ", with QueryStatManager = " + on);
+
+        QueryStatDto[] top = qs.getSlowQueries();
+        assertNotNull("Query Top should not be null", top);
+        assertEquals("Query Top should contain entries ",
+                Math.min(queueSize, runTimes), top.length);
+    }
+
+    private double doStatTest(int times) throws Exception {
+
+        long total = 0;
+        for (int i = 0; i < times; i++) {
+            long start = System.currentTimeMillis();
+            Query q = superuser.getWorkspace().getQueryManager()
+                    .createQuery("SELECT * FROM [nt:base]", Query.JCR_SQL2);
+            q.execute();
+            long dur = System.currentTimeMillis() - start;
+            total += dur;
+        }
+        return (double) total / times;
+    }
+}
Index: src/test/java/org/apache/jackrabbit/core/jmx/registry/JmxSupportTest.java
===================================================================
--- src/test/java/org/apache/jackrabbit/core/jmx/registry/JmxSupportTest.java	(revision 0)
+++ src/test/java/org/apache/jackrabbit/core/jmx/registry/JmxSupportTest.java	(revision 0)
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.jackrabbit.core.jmx.registry;
+
+import java.lang.management.ManagementFactory;
+
+import javax.management.MBeanInfo;
+import javax.management.MBeanOperationInfo;
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.apache.jackrabbit.core.jmx.AbstractStatTest;
+import org.apache.jackrabbit.core.jmx.JackrabbitBaseMBean;
+import org.apache.jackrabbit.core.jmx.core.CoreStatManagerMBean;
+import org.apache.jackrabbit.core.jmx.query.QueryStatManagerMBean;
+
+/**
+ * Performs various JMX test cases.
+ */
+public class JmxSupportTest extends AbstractStatTest {
+
+    private final MBeanServer server = ManagementFactory
+            .getPlatformMBeanServer();
+
+    public void testInit() {
+        assertFalse(lookupDomain(server, JackrabbitBaseMBean.DOMAIN));
+        enableJxmRegistry();
+        assertTrue(lookupDomain(server, JackrabbitBaseMBean.DOMAIN));
+        statManager.stop();
+        assertFalse(lookupDomain(server, JackrabbitBaseMBean.DOMAIN));
+    }
+
+    public void testDynamicRegistry() {
+        enableJxmRegistry();
+
+        assertTrue(lookupMBean(server, JmxRegistryManagerMBean.NAME));
+        assertFalse(lookupMBean(server, CoreStatManagerMBean.NAME));
+        assertFalse(lookupMBean(server, QueryStatManagerMBean.NAME));
+
+        assertTrue(runMBeanMethod(server, JmxRegistryManagerMBean.NAME,
+                "enableCoreStatJmx"));
+        assertTrue(lookupMBean(server, CoreStatManagerMBean.NAME));
+        assertFalse(lookupMBean(server, QueryStatManagerMBean.NAME));
+
+        assertTrue(runMBeanMethod(server, JmxRegistryManagerMBean.NAME,
+                "enableQueryStatJmx"));
+        assertTrue(lookupMBean(server, CoreStatManagerMBean.NAME));
+        assertTrue(lookupMBean(server, QueryStatManagerMBean.NAME));
+
+    }
+
+    private boolean lookupDomain(MBeanServer server, String domain) {
+        boolean found = false;
+        String domains[] = server.getDomains();
+        for (int i = 0; i < domains.length; i++) {
+            if (domain.equals(domains[i])) {
+                found = true;
+                break;
+            }
+        }
+        return found;
+    }
+
+    private boolean lookupMBean(MBeanServer server, String name) {
+        try {
+            final ObjectName on = new ObjectName(name);
+            return server.isRegistered(on);
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    private boolean runMBeanMethod(MBeanServer server, String name,
+            String method) {
+        try {
+            final ObjectName on = new ObjectName(name);
+            MBeanInfo mi = server.getMBeanInfo(on);
+            for (MBeanOperationInfo op : mi.getOperations()) {
+                if (method.equals(op.getName())) {
+                    server.invoke(on, method, null, null);
+                    return true;
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+        return false;
+    }
+}
