Tag: JMX

Creating and Registering MXBean in JBossAS7.1.1

Hi,

JBossAS7 provides useful ways to create our own custom MBeans using SAR archives as mentioned in our previous articles. Now in this current demo we will see how we can create and and register our own custom “MXBean” in JBossAS7.

An MXBean is a kind of MBean. An MXBean object can be registered directly in the MBean Server, or it can be used as an argument to StandardMBean and the resultant MBean registered in the MBean Server. These beans have an annotation @MXBean(true) or just @MXBean. The MXBean concept provides a simple way to code an MBean that only references a predefined set of types, the ones defined by javax.management.openmbean. In this way, you can be sure that your MBean will be usable by any client, including remote clients, without any requirement that the client have access to model-specific classes representing the types of your MBeans.

More infrmation on @MXBean annotation can be found in the following link:
http://docs.oracle.com/javase/6/docs/api/javax/management/MXBean.html

NOTE: the Codes related to this demo are available in the Github repository:
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/MXBeanDemo

Step-1). Here we are using JBoss AS7.1.1 Final (“jboss-as-7.1.1.Final”) which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Step-2). Create a directory with the name “src” somewhere in your file system like “/home/userone/MXBeanDemo/”. Inside the “src” directory we are going to place our all source code and xml files for development.

Step-3). Now we will write a simple interface “HelloWorldServiceMBean.java” inside “/home/userone/MXBeanDemo/src” as following

package test.startup;
import javax.management.*;

@MXBean
public interface HelloWorldServiceMBean
  {
     public String getMessage();
     public void setMessage(String message);
   
     public void printMessage();
  }

Step-3). Now we will write a Simple java program which will using the @MXBean and will provide the implementation of above interface, so write a Class “HelloWorldService.java” inside “/home/userone/MXBeanDemo/src” as following:

package test.startup;

public class HelloWorldService implements HelloWorldServiceMBean
{
   private String message = "Sorry no message today";


   public HelloWorldService()
   {
       System.out.println("ntHelloWorldService() Initialized");
   }

   public String getMessage()
   {
      System.out.println("ntgetMessage() : "+message);
      return message;
   }

   public void setMessage(String message)
   {
      System.out.println("ntsetMessage() : "+message);
      this.message = message;
   }

   public void printMessage()
   {
      System.out.println("ntprintMessage() : "+message);
   }

}

Step-4). Write a simple “index.jsp” file inside “/home/userone/MXBeanDemo/src” as following (This simple JSP will actually create the above mentioned) :

   <%@ page import="javax.management.*,javax.management.remote.*,test.startup.*" %>


  <%
     MBeanServer mbeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer(); 
     System.out.println("Got the MBeanServer.... "+mbeanServer);

     ObjectName objectName=new ObjectName("test.startup:service=HelloWorld");

     HelloWorldServiceMBean bean=new HelloWorldService();
     mbeanServer.registerMBean(bean, objectName); 
     System.out.println("MBean Registered with ObjectName:  "+objectName);
  %>

<h1> Check the JBossAS7 Console to see if Your MXBean  is registered properly or not.   You can also use the "$JBOSS_HOME/bin/jconsole.sh" script as well to start the JConsole and to see if the MXBean is accessible through it or not </h1>

Step-5). Now we will write a simple “web.xml” file inside “/home/userone/MXBeanDemo/src” as following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

</web-app>

Step-6). Now in order to build and deploy the above application we will write a very simple ant build script “build.xml” inside “/home/userone/jboss-as-7.1.1.Final/standalone/TESTING/MXBeanDemo” as following:

<project name="MXBeanDemo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.1.Final" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="MXBeanDemo.war" />

        <path id="jboss.classpath">
             <fileset dir="${jboss.module.dir}">
                 <include name="**/*.jar"/>
             </fileset>
        </path>

        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
        </target>

        <target name="build" depends="init">
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy todir="${tmp.dir}/WEB-INF/classes">
                <fileset dir="${src.dir}" includes="**/*.java"/>
           </copy>
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>
           <copy file="${src.dir}/web.xml" tofile="${tmp.dir}/WEB-INF/web.xml"/>      
           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true"/> 

           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>

        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step-7). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step-7). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/jboss-as-7.1.0.Final/standalone/TESTING/MXBeanDemo” and then run the ant to build & deploy the webapplication. by running the command “ant deploy”

[userone@localhost MXBeanDemo]$ ant 

Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/MXBeanDemo/build
    [mkdir] Created dir: /home/userone/MXBeanDemo/build
    [mkdir] Created dir: /home/userone/MXBeanDemo/tmp
    [mkdir] Created dir: /home/userone/MXBeanDemo/tmp/WEB-INF/classes

build:
    [javac] Compiling 2 source files to /home/userone/MXBeanDemo/tmp/WEB-INF/classes
     [copy] Copying 2 files to /home/userone/MXBeanDemo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/MXBeanDemo/tmp
     [copy] Copying 1 file to /home/userone/MXBeanDemo/tmp/WEB-INF
      [jar] Building jar: /home/userone/MXBeanDemo/tmp/MXBeanDemo.war
     [copy] Copying 1 file to /home/userone/MXBeanDemo/build

deploy:
     [echo] *******************  Deploying the WAR file MXBeanDemo.war *********************
     [echo] ********** build/MXBeanDemo.war to /home/userone/jboss-as-7.1.1.Final/standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.1.Final/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 6 seconds

Step-8). Now you will able to access your application. “http://localhost:8080/MXBeanDemo/index.jsp” then you will see the following kind of output on your JBossAS7 Console as following:


11:57:32,024 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-7) JBAS015877: Stopped deployment MXBeanDemo.war in 34ms
11:57:32,026 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015876: Starting deployment of "MXBeanDemo.war"
11:57:32,078 INFO  [org.jboss.web] (MSC service thread 1-6) JBAS018210: Registering web context: /MXBeanDemo
11:57:32,190 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 1) JBAS018565: Replaced deployment "MXBeanDemo.war" with deployment "MXBeanDemo.war"
11:57:54,160 INFO  [stdout] (http--127.0.0.1-8080-2) Got the MBeanServer.... org.jboss.as.jmx.PluggableMBeanServerImpl@3c21251c
11:57:54,161 INFO  [stdout] (http--127.0.0.1-8080-2) 
11:57:54,162 INFO  [stdout] (http--127.0.0.1-8080-2) 	HelloWorldService() Initialized
11:57:54,165 INFO  [stdout] (http--127.0.0.1-8080-2) MBean Registered with ObjectName:  test.startup:service=HelloWorld

Verifying using JConsole

Step-9). Start the jconsole using the JBoss provided script “jboss-as-7.1.1.Final/bin/jconsole.sh” (Make sure that you set the JAVA_HOME properly in the script)

Connecting to JBossAS7 using JConsole

Connecting to JBossAS7 using JConsole

See your MXBean is available on JConsole

See your MXBean is available on JConsole


.
.
Thanks
Middleware Magic Team :)


Accessing JBossAS7 HornetQ Related statistics using JMX remotely

Hi,

During initial builds of JBoss AS7 the MBean access methodology was kee changing, even the JMX subsystem XSD “jboss-as-jmx_1_1.xsd” also changed a lot from JBossAS7.0 till JBossAS7.1.1 Final. So here we are going to see How can we access the JBoss HornetQ/messaging related MBeans Remotely & Programatically. Here are the following points which we will notice as part of this article:

Point-1). Accessing MBeans using the JBoss Remoting Port 4447 on JBoss AS7.1.1.Final. In our previos demo (http://middlewaremagic.com/jboss/?p=1846) JMX code we used Native management Port 9999 in order to access the MBeans remotely. Now we will use 4447 port to do the same.

Point-2). The jmx subsystem inside our JBoss configuration file like “standalone-full.xml” should look something like following:

        <subsystem xmlns="urn:jboss:domain:jmx:1.1">
            <show-model value="true"/>
             <remoting-connector  use-management-endpoint="false" />
        </subsystem>

Here If the value of “use-management-endpoint” is “false” then this connector will use the remoting port 4447 for the jmx operations.
Point-3). Connecting to JBoss AS7 using JConsole Remotely.

Point-4). Connecting to JBoss AS7 using VisualVM Remotely.

Accessing HornetQ related MBeans Programatically Remotely/Locally

Step-1). As we know that messaging subsystem is available in “standalone-full.xml” or “standalong-full-ha.xml” profiles so after making the changes in oyur configuration file as mentioned in Point-2), Start your JBoss AS7.1.1 Final like following

     ./standalone.sh  -c standalone-full.xml -b 10.10.10.10  -bmanagement 10.10.10.10

Here wec can see that you can start JBossAS7 in a particular Bind address as well. “-b” option can be used to define the Public Interface bind address, where as “-bmanagement” is used to assign a same or different Bind Address for the Management Interface. To maintain security of your Management Interaface you can run it in a secured Host address or in localhost using -bmanagement.

Step-2). Write a Simple Class “JMSAccess.java” inside “/home/userone/JmxDemo/” as following:

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.*;

public class JMSAccess {
    public static void main(String[] args) throws Exception {
        String host = "localhost";  // Your JBoss Bind Address default is localhost
        int port = 4447;  // JBoss remoting port

        /*
          4447 can be enabled in your JBoss Configuration file with the help of the following configuration in your JBoss configuration file
          <subsystem xmlns="urn:jboss:domain:jmx:1.1">
              <show-model value="true"/>
               <remoting-connector  use-management-endpoint="false" />
          </subsystem>
        */

        String urlString ="service:jmx:remoting-jmx://" + host + ":" + port;
        System.out.println("		nnt****  urlString: "+urlString);

        JMXServiceURL serviceURL = new JMXServiceURL(urlString);
        JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
        MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();


        ObjectName objectName=new ObjectName("jboss.as:subsystem=messaging,hornetq-server=default");

        Integer threadPoolMaxSize=(Integer)connection.getAttribute(objectName, "threadPoolMaxSize");
        Boolean clustered=(Boolean)connection.getAttribute(objectName, "clustered");
        Boolean createBindingsDir=(Boolean)connection.getAttribute(objectName, "createBindingsDir");
        Long journalBufferSize=(Long)connection.getAttribute(objectName, "journalBufferSize");
        Long securityInvalidationInterval=(Long)connection.getAttribute(objectName, "securityInvalidationInterval");
        Boolean messageCounterEnabled=(Boolean)connection.getAttribute(objectName, "messageCounterEnabled");
        Integer journalCompactMinFiles=(Integer)connection.getAttribute(objectName, "journalCompactMinFiles");
        String journalType=(String)connection.getAttribute(objectName, "journalType");
        Boolean journalSyncTransactional=(Boolean)connection.getAttribute(objectName, "journalSyncTransactional");
        Integer scheduledThreadPoolMaxSize=(Integer)connection.getAttribute(objectName, "scheduledThreadPoolMaxSize");
        Boolean securityEnabled=(Boolean)connection.getAttribute(objectName, "securityEnabled");
        String jmxDomain=(String)connection.getAttribute(objectName, "jmxDomain");
        Long transactionTimeout=(Long)connection.getAttribute(objectName, "transactionTimeout");
        String clusterPassword=(String)connection.getAttribute(objectName, "clusterPassword");
        Boolean createJournalDir=(Boolean)connection.getAttribute(objectName, "createJournalDir");
        Long messageCounterSamplePeriod=(Long)connection.getAttribute(objectName, "messageCounterSamplePeriod");
        Boolean persistenceEnabled=(Boolean)connection.getAttribute(objectName, "persistenceEnabled");
        Boolean allowFailback=(Boolean)connection.getAttribute(objectName, "allowFailback");
        Long transactionTimeoutScanPeriod=(Long)connection.getAttribute(objectName, "transactionTimeoutScanPeriod");
        Boolean jmxManagementEnabled=(Boolean)connection.getAttribute(objectName, "jmxManagementEnabled");
        String securityDomain=(String)connection.getAttribute(objectName, "securityDomain");
        Long serverDumpInterval=(Long)connection.getAttribute(objectName, "serverDumpInterval");	
        Long failbackDelay=(Long)connection.getAttribute(objectName, "failbackDelay");
        Integer idCacheSize=(Integer)connection.getAttribute(objectName, "idCacheSize");
        Long messageExpiryScanPeriod=(Long)connection.getAttribute(objectName, "messageExpiryScanPeriod");
        Boolean wildCardRoutingEnabled=(Boolean)connection.getAttribute(objectName, "wildCardRoutingEnabled");
        Integer messageCounterMaxDayHistory=(Integer)connection.getAttribute(objectName, "messageCounterMaxDayHistory");
        Boolean started=(Boolean)connection.getAttribute(objectName, "started");


        System.out.println("	threadPoolMaxSize              = "+threadPoolMaxSize);
        System.out.println("	clustered                      = "+clustered);
        System.out.println("	createBindingsDir              = "+createBindingsDir);
        System.out.println("	journalBufferSize              = "+journalBufferSize);
        System.out.println("	securityInvalidationInterval   = "+securityInvalidationInterval);
        System.out.println("	messageCounterEnabled          = "+messageCounterEnabled);
        System.out.println("	journalType                    = "+journalType);
        System.out.println("	journalSyncTransactional       = "+journalSyncTransactional);
        System.out.println("	scheduledThreadPoolMaxSize     = "+scheduledThreadPoolMaxSize);
        System.out.println("	securityEnabled                = "+securityEnabled);
        System.out.println("	jmxDomain                      = "+jmxDomain);
        System.out.println("	transactionTimeout             = "+transactionTimeout);
        System.out.println("	clusterPassword                = "+clusterPassword);
        System.out.println("	createJournalDir               = "+createJournalDir);
        System.out.println("	messageCounterSamplePeriod     = "+messageCounterSamplePeriod);
        System.out.println("	persistenceEnabled             = "+persistenceEnabled);
        System.out.println("	allowFailback                  = "+allowFailback);
        System.out.println("	transactionTimeoutScanPeriod   = "+transactionTimeoutScanPeriod);
        System.out.println("	jmxManagementEnabled           = "+jmxManagementEnabled);
        System.out.println("	securityDomain                 = "+securityDomain);
        System.out.println("	serverDumpInterval             = "+serverDumpInterval);
        System.out.println("	failbackDelay                  = "+failbackDelay);
        System.out.println("	idCacheSize                    = "+idCacheSize);
        System.out.println("	messageExpiryScanPeriod        = "+messageExpiryScanPeriod);
        System.out.println("	wildCardRoutingEnabled         = "+wildCardRoutingEnabled);
        System.out.println("	messageCounterMaxDayHistory    = "+messageCounterMaxDayHistory);
        System.out.println("	started                        = "+started);


        jmxConnector.close();
    }
}

***NOTE***: In the above program we are trying to access various attributes present inside the ObjectName “jboss.web:type=Manager,path=/Log4jDemo,host=default-host” where “Log4jDemo” is the Context-Root of My WebApplication which i wanted to monitor. And th edefault Host-Name is “default-host”, In your case these values might be different so better use the JConsole to connect to JBoss Locally and then get the exact Object name from it.

Step-3). Now oipen a Terminal where we need to set the PATh and CLASSPATH like following:

For UNIX Based Operating System:

export PATH=/home/userone/jdk1.6.0_21/bin:$PATH
export CLASSPATH=/home/userone/jboss-as-7.1.1.Final/bin/client/jboss-client.jar:$CLASSPATH:.:

++++++++++++++++++++++++++++++++
For Windows Based Operating System

set PATH=C:jdk1.6.0_21bin;%PATH%
set CLASSPATH=c:jboss-as-7.1.1.Finalbinclientjboss-client.jar;%CLASSPATH%;.;

***NOTE***: It is must that your JMX Client should include the “jboss-client.jar” in it’s classpath as above.

Step-4). Now compile and run the above program:

[userone@localhost JmxDemo]$ javac JMSAccess.java
[userone@localhost JmxDemo]$ java JMSAccess

		

	****  urlString: service:jmx:remoting-jmx://localhost:4447
Jun 3, 2012 8:13:27 PM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
Jun 3, 2012 8:13:28 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
Jun 3, 2012 8:13:28 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA
	threadPoolMaxSize              = 30
	clustered                      = false
	createBindingsDir              = true
	journalBufferSize              = null
	securityInvalidationInterval   = 10000
	messageCounterEnabled          = false
	journalType                    = ASYNCIO
	journalSyncTransactional       = true
	scheduledThreadPoolMaxSize     = 5
	securityEnabled                = true
	jmxDomain                      = org.hornetq
	transactionTimeout             = 300000
	clusterPassword                = CHANGE ME!!
	createJournalDir               = true
	messageCounterSamplePeriod     = 10000
	persistenceEnabled             = true
	allowFailback                  = true
	transactionTimeoutScanPeriod   = 1000
	jmxManagementEnabled           = false
	securityDomain                 = other
	serverDumpInterval             = -1
	failbackDelay                  = 5000
	idCacheSize                    = 2000
	messageExpiryScanPeriod        = 30000
	wildCardRoutingEnabled         = true
	messageCounterMaxDayHistory    = 10
	started                        = true

Accessing MBeans using JConsole LOCALLY

Start the Server and Open the “$JAVA_HOME/bin/jconsole” . jconsole will be able to detect any locally running JAVA process just connect to your JBoss process through it then you will be able to see the following kind of JBoss MBeans inside jconsole:

JConsole_WebContainerMBean_Access_JBossAS711

Accessing MBeans using JConsole REMOTELY

If you want to start your JConsole in order to connect to JBoss remotely then you should use the “jboss-as-7.1.1.Final/bin/jconsole.sh” script provided by JBoss, which does additional classpath settings which is required in order to use the JBoss implementation of the mbeans.

Oncew you run the “jboss-as-7.1.1.Final/bin/jconsole.sh” then you can choose the “Remote Process” option in “New Connection” wizard of your JConsole then you can use the following kind of address in order to connect to JBoss AS7

service:jmx:remoting-jmx://jbossHost:4447
OR
service:jmx:remoting-jmx://jbossHost:9999

The port can be decided based on the Point-2). mentioned above.

Accessing MBeans using VisualVM REMOTELY

There is a good script developed by “Mr. John O’Hara” as mentioned in the community link: https://community.jboss.org/thread/196428 Which can be used to connect to JBoss using VisualVM.

https://github.com/johnaoahra80/jboss-as-tool-integration/blob/master/visualvm/visualvm.sh

For below script all the credit goes to “Mr. John O’Hara”


#!/bin/sh

DIRNAME=`dirname "$0"`
GREP="grep"

# Use the maximum available, or set MAX_FD != -1 to use that
MAX_FD="maximum"

# OS specific support (must be 'true' or 'false').
cygwin=false;
darwin=false;
linux=false;
case "`uname`" in
    CYGWIN*)
        cygwin=true
        ;;

    Darwin*)
        darwin=true
        ;;

    Linux)
        linux=true
        ;;
esac

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
    [ -n "$JBOSS_HOME" ] &&
        JBOSS_HOME=`cygpath --unix "$JBOSS_HOME"`
    [ -n "$JAVA_HOME" ] &&
        JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
    [ -n "$JAVAC_JAR" ] &&
        JAVAC_JAR=`cygpath --unix "$JAVAC_JAR"`
fi

# Setup JBOSS_HOME
RESOLVED_JBOSS_HOME=`cd "$DIRNAME/.."; pwd`
if [ "x$JBOSS_HOME" = "x" ]; then
    # get the full path (without any relative bits)
    JBOSS_HOME=$RESOLVED_JBOSS_HOME
else
 SANITIZED_JBOSS_HOME=`cd "$JBOSS_HOME"; pwd`
 if [ "$RESOLVED_JBOSS_HOME" != "$SANITIZED_JBOSS_HOME" ]; then
   echo "WARNING JBOSS_HOME may be pointing to a different installation - unpredictable results may occur."
   echo ""
 fi
fi
export JBOSS_HOME

# Setup the JVM
if [ "x$JAVA" = "x" ]; then
    if [ "x$JAVA_HOME" != "x" ]; then
        JAVA="$JAVA_HOME/bin/java"
    else
        JAVA="java"
    fi
fi

if [ "x$JBOSS_MODULEPATH" = "x" ]; then
    JBOSS_MODULEPATH="$JBOSS_HOME/modules"
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
    JBOSS_HOME=`cygpath --path --windows "$JBOSS_HOME"`
    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
    JBOSS_CLASSPATH=`cygpath --path --windows "$JBOSS_CLASSPATH"`
    JBOSS_ENDORSED_DIRS=`cygpath --path --windows "$JBOSS_ENDORSED_DIRS"`
    JBOSS_MODULEPATH=`cygpath --path --windows "$JBOSS_MODULEPATH"`
fi

CLASSPATH=""
# CLASSPATH=$CLASSPATH:$JAVA_HOME/lib/tools.jar

MODULES="org/jboss/remoting3/remoting-jmx org/jboss/remoting3 org/jboss/logging org/jboss/xnio org/jboss/xnio/nio org/jboss/sasl org/jboss/marshalling org/jboss/marshalling/river"

for MODULE in $MODULES
do
    for JAR in `cd "$JBOSS_MODULEPATH/$MODULE/main/" && ls -1 *.jar`
    do
        CLASSPATH="$CLASSPATH:$JBOSS_MODULEPATH/$MODULE/main/$JAR"
    done
done


jvisualvm -cp:a $CLASSPATH


.
.
Thanks :)
Middleware Magic Team


Expiring HttpSessions associated with a WebApp using JMX client in JBossAS7.1.1

Hi,

During various builds of JBoss AS7 the MBean access methodology was keep changing, even the JMX subsystem XSD “jboss-as-jmx_1_1.xsd” also changed a lot from JBossAS7.0 till JBossAS7.1.1 Final. So here we are going to see How can we access the HttpSessions associated with a particular webapplication deployed on JBoss with the help of MBeans Remotely & Programatically. Here are the following points which we will notice as part of this article:

Point-1). Listing and Expiring all the HttpSessions related to a particular WebApplication using JMX.

Point-2). Accessing MBeans using the JBoss Native Management port 9999 on JBoss AS7.1.1.Final.

Point-3). The jmx subsystem inside our JBoss configuration file like “standalone-full.xml” should look something like following:

        <subsystem xmlns="urn:jboss:domain:jmx:1.1">
            <show-model value="true"/>
             <remoting-connector  use-management-endpoint="true" />
        </subsystem>

Here If the value of “use-management-endpoint” is “true” then this connector will use the management endpoint, otherwise it will use the remoting subsystem endpoint.

Point-4). Here we will also need to make sure that we enable the following System Property in the JBoss Cofiguration file (standalone*.xml) So that JBoss will make the “jboss.web:type=Manager” access available for the remote JMX Clients.

    <system-properties>
        <property name="org.apache.tomcat.util.ENABLE_MODELER" value="true"/>
    </system-properties>

***NOTE***: If you will not add the above System property for your JBoss then JBoss will not expose some of the MBeans which are available as part of “jboss.web:type=*”

Expiring HttpSessions programatically Remotely/Locally

Step-1). After enabling the System property org.apache.tomcat.util.ENABLE_MODELER=true on your JBoss, Start your JBoss AS7.1.1 Final like following

     ./standalone.sh  -c standalone-full.xml

You can also start it in a particular Bind address as well.

Step-2). Write a Simple Class “JMXBasedHttpSessionManagement.java” inside “/home/userone/JmxDemo/” as following:

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.*;
import java.util.*;

public class JMXBasedHttpSessionManagement { 
    
    private String jbossHost;
    private int jbossMgmtPort;
    private MBeanServerConnection connection;
    private JMXConnector jmxConnector;

    public JMXBasedHttpSessionManagement(String jbossHost,int jbossMgmtPort)throws Exception
        {
          this.jbossMgmtPort=jbossMgmtPort;
          this.jbossHost=jbossHost;
          String urlString ="service:jmx:remoting-jmx://" + jbossHost + ":" + jbossMgmtPort;
          JMXServiceURL serviceURL = new JMXServiceURL(urlString);
          jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
          connection = jmxConnector.getMBeanServerConnection();          
        }


    public void showSessionDetails(ObjectName objectName) throws Exception
        {
          System.out.println("nn********************* Details of "+objectName+" *********************");
          Integer sessionMaxAliveTime=(Integer)connection.getAttribute(objectName, "sessionMaxAliveTime");
          Integer maxInactiveInterval=(Integer)connection.getAttribute(objectName, "maxInactiveInterval");
          Integer activeSessions=(Integer)connection.getAttribute(objectName, "activeSessions");
          Integer sessionCounter=(Integer)connection.getAttribute(objectName, "sessionCounter");
          Integer sessionAverageAliveTime=(Integer)connection.getAttribute(objectName, "sessionAverageAliveTime");
          Long processingTime=(Long)connection.getAttribute(objectName, "processingTime");
          Integer sessionIdLength=(Integer)connection.getAttribute(objectName, "sessionIdLength");
          Integer maxActive=(Integer)connection.getAttribute(objectName, "maxActive");
          Integer maxActiveSessions=(Integer)connection.getAttribute(objectName, "maxActiveSessions");
          Integer expiredSessions=(Integer)connection.getAttribute(objectName, "expiredSessions");
          Integer rejectedSessions=(Integer)connection.getAttribute(objectName, "rejectedSessions");

          System.out.println("	maxInactiveInterval     = "+maxInactiveInterval);
          System.out.println("	activeSessions          = "+activeSessions);
          System.out.println("	sessionCounter          = "+sessionCounter);
          System.out.println("	sessionAverageAliveTime = "+sessionAverageAliveTime);
          System.out.println("	sessionAverageAliveTime = "+sessionAverageAliveTime);
          System.out.println("	processingTime          = "+processingTime);
          System.out.println("	sessionIdLength         = "+sessionIdLength);
          System.out.println("	maxActiveSessions       = "+maxActiveSessions);
          System.out.println("	maxActive               = "+maxActive);
          System.out.println("	expiredSessions         = "+expiredSessions);
        }

     // Following methd can be used to list all the HttpSessions associated with a particular web application.
    public void listSessionIds(ObjectName objectName) throws Exception
        {
          System.out.println("nn********************* JSESSIONID Details for "+objectName+" *********************");
          String sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          StringTokenizer tokenizer=new StringTokenizer(sessionIdList," ");
          System.out.println("Total Active HttpSessions: "+tokenizer.countTokens()+"n");
          int counter=0;
          while(tokenizer.hasMoreTokens())
             {
                System.out.println(++counter+"tt"+tokenizer.nextToken());
             }
         }

   
          //Following  method can be used to expire a Specific HttpSession associated with a particular Web Application. It requires that you should already have the JSESSIONID of the HttpSession which you want to expire.
     
    public void expireSession(ObjectName objectName, String jsessionId) throws Exception
        {
          String sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          StringTokenizer tokenizer=new StringTokenizer(sessionIdList," ");
          System.out.println("BEFORE expiration Total HttpSessions: "+tokenizer.countTokens());

          System.out.println("*** Expiring JSESSIONID " + jsessionId + " t"+objectName+" ***");
          connection.invoke(objectName,"expireSession", new String[]{jsessionId},  new String[]{"java.lang.String"});

          sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          tokenizer=new StringTokenizer(sessionIdList," ");
          System.out.println("*** AFTER expiration Total HttpSessions: "+tokenizer.countTokens());
         }
    
      // Following  method can be used to expire All the HttpSessions associated with a particular Web Application
    public void expireAllSession(ObjectName objectName) throws Exception
        {
          String sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          StringTokenizer tokenizer=new StringTokenizer(sessionIdList," ");

          int counter=0;
          while(tokenizer.hasMoreTokens())
             {
                String jsessionId=tokenizer.nextToken();
                connection.invoke(objectName,"expireSession", new String[]{jsessionId},  new String[]{"java.lang.String"});                
                System.out.println("t Expired Session "+ (++counter)  +"ttJSESSIONID= "+jsessionId);
             }
         }


    public static void main(String[] args) throws Exception {
        String jbossHost="localhost";
        int jbossMgmtPort=9999;
        String contextRootOfYourWebApp="Log4jDemo";

        JMXBasedHttpSessionManagement client=new JMXBasedHttpSessionManagement(jbossHost,jbossMgmtPort);
        ObjectName objectName=new ObjectName("jboss.web:type=Manager,path=/"+contextRootOfYourWebApp+",host=default-host");

        client.showSessionDetails(objectName);

        // EXAMPLE of ObjectName:    jboss.web:type=Manager,path=/Log4jDemo,host=default-host
        client.listSessionIds(objectName);

        // Call the following  method by passing a Specific HttpSession ID to expire it.
        //client.expireSession(objectName,"sFO2tCKf+-qPYZCkUHaia8Aa.undefined");

        // Call the following method to expire all the JSESSIONID s 
        System.out.println("nn*********************  Expiring All the HttpSession related to "+objectName);
        client.expireAllSession(objectName);

        client.listSessionIds(objectName);
        client.jmxConnector.close();
    }

}

***NOTE***: In the above program we are trying to access various attributes present inside the ObjectName “jboss.web:type=Manager,path=/Log4jDemo,host=default-host” where “Log4jDemo” is the Context-Root of My WebApplication which i wanted to monitor. And th edefault Host-Name is “default-host”, In your case these values might be different so better use the JConsole to connect to JBoss Locally and then get the exact Object name from it.

Step-3). Now oipen a Terminal where we need to set the PATh and CLASSPATH like following:

For UNIX Based Operating System:

export PATH=/home/userone/jdk1.6.0_21/bin:$PATH
export CLASSPATH=/home/userone/jboss-as-7.1.1.Final/bin/client/jboss-client.jar:$CLASSPATH:.:

++++++++++++++++++++++++++++++++
For Windows Based Operating System

set PATH=C:jdk1.6.0_21bin;%PATH%
set CLASSPATH=c:jboss-as-7.1.1.Finalbinclientjboss-client.jar;%CLASSPATH%;.;

***NOTE***: It is must that your JMX Client should include the “jboss-client.jar” in it’s classpath as above.

Step-4). Now compile and run the above program:

[userone@localhost JmxDemo]$ javac JMXBasedHttpSessionManagement.java 
[userone@localhost JmxDemo]$ java JMXBasedHttpSessionManagement 
May 20, 2012 12:20:01 PM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
May 20, 2012 12:20:01 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
May 20, 2012 12:20:01 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA


********************* Details of jboss.web:type=Manager,path=/Log4jDemo,host=default-host *********************
	maxInactiveInterval     = 1800
	activeSessions          = 4
	sessionCounter          = 133
	sessionAverageAliveTime = 1386
	sessionAverageAliveTime = 1386
	processingTime          = 59
	sessionIdLength         = 18
	maxActiveSessions       = -1
	maxActive               = 100
	expiredSessions         = 130


********************* JSESSIONID Details for jboss.web:type=Manager,path=/Log4jDemo,host=default-host *********************
Total Active HttpSessions: 4

1		7paBncdqzoq1vXJHSB645jTB.undefined
2		Cy4QPyubiydfIrYD9A98B-Cs.undefined
3		6bdfUey9mXAA-y1tJo8xi508.undefined
4		U-57RR-B+bHhZicveBIYvhoq.undefined


*********************  Expiring All the HttpSession related to jboss.web:type=Manager,path=/Log4jDemo,host=default-host
	 Expired Session 1		JSESSIONID= 7paBncdqzoq1vXJHSB645jTB.undefined
	 Expired Session 2		JSESSIONID= Cy4QPyubiydfIrYD9A98B-Cs.undefined
	 Expired Session 3		JSESSIONID= 6bdfUey9mXAA-y1tJo8xi508.undefined
	 Expired Session 4		JSESSIONID= U-57RR-B+bHhZicveBIYvhoq.undefined


********************* JSESSIONID Details for jboss.web:type=Manager,path=/Log4jDemo,host=default-host *********************
Total Active HttpSessions: 0

.
.
Thanks :)
Middleware Magic Team


Copyright © 2010-2012 Middleware Magic. All rights reserved. |