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("\n\tHelloWorldService() Initialized");
   }

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

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

   public void printMessage()
   {
      System.out.println("\n\tprintMessage() : "+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("		\n\n\t****  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_21\bin;%PATH%
set CLASSPATH=c:\jboss-as-7.1.1.Final\bin\client\jboss-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("\n\n********************* 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("\n\n********************* 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+"\t\t"+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)  +"\t\tJSESSIONID= "+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("\n\n*********************  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_21\bin;%PATH%
set CLASSPATH=c:\jboss-as-7.1.1.Final\bin\client\jboss-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


Accessing “jboss.web:type=*” MBeans Programmatically in JBossAS7.1.1

Hi,

During various 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 MBeans Remotely & Programatically. Here are the following points which we will notice as part of this article:

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

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="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-3). 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=*”

Accessing MBeans 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 “JBossJMXClient.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 JBossJMXClient {
    public static void main(String[] args) throws Exception {
        String host = "localhost";  // Your JBoss Bind Address default is localhost
        int port = 9999;  // management-native port

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

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

        //Invoke on the JBoss AS MBean server
        int count = connection.getMBeanCount();
        System.out.println(count);

        ObjectName objectName=new ObjectName("jboss.web:type=Manager,path=/Log4jDemo,host=default-host");
        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);

        jmxConnector.close();
    }
}

/*  Make sure that the following System property is enable in your JBoss

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

***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_21\bin;%PATH%
set CLASSPATH=c:\jboss-as-7.1.1.Final\bin\client\jboss-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 JBossJMXClient.java
[userone@localhost JmxDemo]$ java JBossJMXClient

	****  urlString: service:jmx:remoting-jmx://localhost:9999

May 20, 2012 9:54:12 AM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
May 20, 2012 9:54:12 AM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
May 20, 2012 9:54:12 AM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA
243
	maxInactiveInterval     = 1800
	activeSessions          = 3
	sessionCounter          = 3
	sessionAverageAliveTime = 0
	sessionAverageAliveTime = 0
	processingTime          = 0
	sessionIdLength         = 18
	maxActiveSessions       = -1
	maxActive               = 3
	expiredSessions         = 0

Accessing MBeans using JConsole Locally

As mentioned earlier that If you will not add the above System property (org.apache.tomcat.util.ENABLE_MODELER=true) for your JBoss then JBoss will not expose some of the MBeans which are available as part of “jboss.web:type=*” So after enabling it Just 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

.
.
Thanks :)
Middleware Magic Team


Listing All MBeans present inside JBossAS7 programatically

Hi,

In this demonstration we will see ow we can get all the MBeans present inside JBoss AS7 CR1b, because many of the developers want to talk to JBoss using their own mbean based java code. In this example we will see that we need not to add any additional JAVA_OPTS in our JBoss configuration files in order to access these MBeans.

Once you get to know the ObjectName of the MBean present inside JBoss AS7 then it becomes very easy to programatically access it’s various operations and attributes. You can refer to some of the previous demos present in middlewaremagic for further research on this direction. For Example: Getting WebService Statistics using MBean Code

JBoss side Configuration

Step1). Open the “/home/userone/jboss-as-7.1.0.CR1b/standalone/configuration/standalone-full.xml” file and edit the subsystem “urn:jboss:domain:jmx:1.1″ as following:

        <subsystem xmlns="urn:jboss:domain:jmx:1.1">
            <show-model value="true"/>
            <jmx-connector registry-binding="jmx-connector-registry" server-binding="jmx-connector-server"/>
        </subsystem>

Step2). Restart your JBoss Profile from “/home/userone/jboss-as-7.1.0.CR1b/bin” directory like following:

[userone@localhost bin]$ ./standalone.sh -c standalone-full.xml

Step3). Now Somewhere in your filesystem (like /home/userone/MBeanDemo directory) write a Java Program “TestMBeanServiceMonitor.java” as following:

import java.util.*;
import java.util.Hashtable;
import java.io.IOException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.MemoryMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;

public class TestMBeanServiceMonitor
{
    private static MBeanServerConnection connection;
    private static JMXConnector connector;
    public static void Connection(String hostname, String port) throws IOException
    {
        Integer portInteger = Integer.valueOf(port);
        Hashtable h = new Hashtable();
        JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+hostname+":"+port+"/jmxrmi");
        connector = JMXConnectorFactory.connect(address,null);
        connection = connector.getMBeanServerConnection();
        System.out.println("GOT THE MBeanServerConnection---SUCCESSFULLY");
    }

    private static void listAllJBossAS7MBeans() throws Exception
    {
        //ObjectName serviceRef=new ObjectName("jboss.as:*");
        ObjectName serviceRef=new ObjectName("*.*:*");
        Set<ObjectName> mbeans = connection.queryNames(serviceRef, null);
        for (ObjectName on : mbeans) {
                  System.out.println("\t ObjectName : "+on);
        }
    }

    private static void getThreadDetails() throws Exception
    {
        ObjectName serviceRef=new ObjectName("java.lang:type=Threading");
        Integer daemonThreadCount=(Integer)connection.getAttribute(serviceRef, "DaemonThreadCount");
        System.out.println("\t daemonThreadCount : "+daemonThreadCount);
    }

    public static void main(String[] args) throws Exception
    {
        String hostname = args[0];
        String port = args[1];
        /*
        ***** The port binding should be defined inside your "standalone-full.xml" file.  *****
        *
        <subsystem xmlns="urn:jboss:domain:jmx:1.1">
            <show-model value="true"/>
            <jmx-connector registry-binding="jmx-connector-registry" server-binding="jmx-connector-server"/>
        </subsystem>
        */

        Connection(hostname, port);
        System.out.println("\n\t All JBoss AS7 MBean Listing \n\n");
        listAllJBossAS7MBeans() ;
    }
}

Step4). Now we will write a simple Ant build script to build and execute the above program. So write an Ant build script “/home/userone/MBeanDemo/build.xml” file in the same directory where the above program is placed.

<project name="JBoss_Monitor" default="run">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.CR1b/" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="base.dir" value="." />

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

   <target name="run">
       <javac srcdir="${base.dir}" destdir="${base.dir}"  includes="TestMBeanServiceMonitor.java" classpathref="jboss.classpath"/>
       <java classname="TestMBeanServiceMonitor">
           <classpath>
              <pathelement location="${base.dir}"/>
              <path refid="jboss.classpath"/>
           </classpath>
           <arg line="localhost 1090"/>
       </java>
   </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 is to point to your own JBoss AS7 directory home directory.

NOTE: Also Make sure that you are writing the correct HostName and Port in the above ant script of your JBoss AS7 here arg line=”localhost 1090″

Step5). 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/apache-ant-1.8.2/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/apache-ant-1.8.2/bin;%PATH%

Step7). Run the command “ant” or “ant run” which will internally build/compile and run our MBean Code

[userone@localhost Monitoring]$ ant
Buildfile: /home/userone/jboss-as-7.1.0.CR1b/standalone/MBeanDemo/build.xml

run:
    [javac] /home/userone/jboss-as-7.1.0.CR1b/standalone/MBeanDemo/build.xml:13: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
     [java] GOT THE MBeanServerConnection---SUCCESSFULLY
     [java]
     [java] 	 All JBoss AS7 MBean Listing
     [java]
     [java]
     [java] 	 ObjectName : jboss.as:core-service=server-environment
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.web
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.remoting
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,remote-destination-outbound-socket-binding=mail-smtp
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=jacorb-ssl
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,cache=simple
     [java] 	 ObjectName : jboss.as:core-service=management,management-interface=native-interface
     [java] 	 ObjectName : jboss.as:deployment=EE6_BeanValidationDemo.war
     [java] 	 ObjectName : jboss.as:subsystem=security,security-domain=jboss-web-policy,authorization=classic
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.weld
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.aries.util
     [java] 	 ObjectName : jboss.as:subsystem=naming
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.connector
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,security-setting=#,role=guest
     [java] 	 ObjectName : jboss.as:subsystem=jca,workmanager=default
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate
     [java] 	 ObjectName : jboss.as:subsystem=logging,logger=org.apache.tomcat.util.modeler
     [java] 	 ObjectName : java.lang:type=MemoryPool,name=Code Cache
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,connection-factory=RemoteConnectionFactory
     [java] 	 ObjectName : jboss.as:deployment=Log4jDemo.war
     [java] 	 ObjectName : jboss.as:subsystem=ee
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,thread-pool=default
     [java] 	 ObjectName : jboss.as:subsystem=webservices,endpoint-config=Standard-Endpoint-Config
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=entity
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=jacorb
     [java] 	 ObjectName : jboss.as:subsystem=datasources,data-source=H2DS
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,service=async
     [java] 	 ObjectName : jboss.as:subsystem=jca,bean-validation=bean-validation
     [java] 	 ObjectName : jboss.as:subsystem=security,security-domain=jboss-ejb-policy
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.jpa
     [java] 	 ObjectName : java.lang:type=MemoryPool,name=PS Eden Space
     [java] 	 ObjectName : java.lang:type=Memory
     [java] 	 ObjectName : jboss.as:deployment=MyDemoMDB.jar
     [java] 	 ObjectName : jboss.as:subsystem=logging,console-handler=CONSOLE
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,cache=passivating
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=jmx-connector-server
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=remoting
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.security
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.ejb3
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.aries.jmx
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.xerces
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.transactions
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-connector=netty-throughput,param=batch-delay
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets
     [java] 	 ObjectName : jboss.as:subsystem=deployment-scanner
     [java] 	 ObjectName : jboss.as:deployment=MyDemoMDB.jar,subsystem=ejb3,message-driven-bean=MyMDB
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,pooled-connection-factory=hornetq-ra
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.logging
     [java] 	 ObjectName : jboss.as:subsystem=jaxrs
     [java] 	 ObjectName : jboss.modules:type=ModuleLoader,name=LocalModuleLoader-3
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=management-native
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default
     [java] 	 ObjectName : jboss.as:subsystem=jca,archive-validation=archive-validation
     [java] 	 ObjectName : jboss.jsr77:j2eeType=JVM,name=default,J2EEServer=default
     [java] 	 ObjectName : jboss.as:deployment=TestWebApp.war,subsystem=web,servlet=servlets.TestServlet
     [java] 	 ObjectName : jboss.jta:type=ObjectStore
     [java] 	 ObjectName : java.lang:type=MemoryPool,name=PS Survivor Space
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.ee
     [java] 	 ObjectName : jboss.as:subsystem=logging,periodic-rotating-file-handler=FILE
     [java] 	 ObjectName : jboss.modules:type=ModuleLoader,name=ModuleLoaderIntegration-7
     [java] 	 ObjectName : jboss.as:subsystem=web,connector=http
     [java] 	 ObjectName : java.lang:type=Compilation
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,core-address=jms.topic.testTopic
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.webconsole
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,core-address=jms.queue.testQueue
     [java] 	 ObjectName : jboss.as:subsystem=osgi,configuration=org.apache.felix.webconsole.internal.servlet.OsgiManager
     [java] 	 ObjectName : jboss.as:subsystem=deployment-scanner,scanner=default
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,jms-queue=testQueue
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.as.osgi.configadmin
     [java] 	 ObjectName : jboss.modules:type=ModuleLoader,name=ServiceModuleLoader-5
     [java] 	 ObjectName : jboss.as:subsystem=jca,bootstrap-context=default
     [java] 	 ObjectName : jboss.as:subsystem=mail
     [java] 	 ObjectName : java.lang:type=Runtime
     [java] 	 ObjectName : jboss.as:deployment=TestWebApp.war
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.netty
     [java] 	 ObjectName : jboss.as:deployment=EE6_BeanValidationDemo.war,subsystem=web,servlet=Faces_Servlet
     [java] 	 ObjectName : jboss.as:subsystem=pojo
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.messaging
     [java] 	 ObjectName : jboss.ws:service=ServerConfig
     [java] 	 ObjectName : jboss.as:management-root=server
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-acceptor=netty-throughput,param=batch-delay
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=timestamps,singleton=eviction
     [java] 	 ObjectName : jboss.as:subsystem=jca,workmanager=default,long-running-threads=default-long-running-threads
     [java] 	 ObjectName : jboss.as:subsystem=jca,cached-connection-manager=cached-connection-manager
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,service=iiop
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.pojo
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=javax.transaction.api
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.felix.eventadmin
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.osgi.compendium
     [java] 	 ObjectName : jboss.jsr77:j2eeType=WebModule,name=TestWebApp.war,J2EEServer=default
     [java] 	 ObjectName : jboss.as:subsystem=threads
     [java] 	 ObjectName : jboss.jsr77:j2eeType=WebModule,name=Log4jDemo.war,J2EEServer=default
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.felix.configadmin
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.sar
     [java] 	 ObjectName : jboss.jsr77:j2eeType=WebModule,name=EE6_BeanValidationDemo.war,J2EEServer=default
     [java] 	 ObjectName : java.util.logging:type=Logging
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.mail
     [java] 	 ObjectName : jboss.msc:type=container,name=jboss-as
     [java] 	 ObjectName : jboss.as:subsystem=infinispan
     [java] 	 ObjectName : com.sun.management:type=HotSpotDiagnostic
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-connector=netty-throughput
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=local-query
     [java] 	 ObjectName : java.lang:type=GarbageCollector,name=PS Scavenge
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,strict-max-bean-instance-pool=mdb-strict-max-pool
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.jsr77
     [java] 	 ObjectName : jboss.as:subsystem=transactions
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.jdr
     [java] 	 ObjectName : jboss.as:subsystem=security,security-domain=other,authentication=classic
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=messaging
     [java] 	 ObjectName : jboss.as:subsystem=security,security-domain=other
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-acceptor=netty-throughput
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.projectodd.stilts
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,strict-max-bean-instance-pool=slsb-strict-max-pool
     [java] 	 ObjectName : jboss.as:subsystem=webservices,endpoint-config=Recording-Endpoint-Config
     [java] 	 ObjectName : jboss.as:core-service=management,security-realm=ManagementRealm,authentication=properties
     [java] 	 ObjectName : jboss.as:deployment=BeanValidation_EJB_Demo.ear
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,security-setting=#
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,in-vm-acceptor=in-vm
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=javax.servlet.api
     [java] 	 ObjectName : jboss.as:subsystem=security,security-domain=jboss-ejb-policy,authorization=classic
     [java] 	 ObjectName : jboss.as:deployment=BeanValidation_EJB_Demo.ear,subdeployment=localEJB.jar,subsystem=ejb3,stateless-session-bean=CallerName
     [java] 	 ObjectName : jboss.as:subsystem=cmp
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=entity,singleton=eviction
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=txn-recovery-environment
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.jaxrs
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,service=timer-service
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.webservices
     [java] 	 ObjectName : java.lang:type=MemoryPool,name=PS Perm Gen
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=local-query,singleton=expiration
     [java] 	 ObjectName : jboss.as:subsystem=webservices
     [java] 	 ObjectName : jboss.as:subsystem=jpa
     [java] 	 ObjectName : jboss.as:core-service=management
     [java] 	 ObjectName : jboss.as:subsystem=logging,logger=jacorb
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.http
     [java] 	 ObjectName : java.lang:type=MemoryPool,name=PS Old Gen
     [java] 	 ObjectName : jboss.as:subsystem=web,configuration=jsp-configuration
     [java] 	 ObjectName : jboss.as:subsystem=web,configuration=static-resources
     [java] 	 ObjectName : jboss.as:subsystem=sar
     [java] 	 ObjectName : jboss.as:core-service=management,security-realm=ManagementRealm
     [java] 	 ObjectName : java.lang:type=GarbageCollector,name=PS MarkSweep
     [java] 	 ObjectName : jboss.as:subsystem=jca,workmanager=default,short-running-threads=default-short-running-threads
     [java] 	 ObjectName : jboss.as:deployment=BeanValidation_EJB_Demo.ear,subdeployment=localEJB.jar
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=txn-status-manager
     [java] 	 ObjectName : jboss.as:deployment=EE6_BeanValidationDemo.war,subsystem=web
     [java] 	 ObjectName : jboss.as:subsystem=osgi,property=org.osgi.framework.startlevel.beginning
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,in-vm-connector=in-vm
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,address-setting=#
     [java] 	 ObjectName : jboss.as:subsystem=ejb3
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.felix.metatype
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.felix.scr
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.felix.log
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.blueprint
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-acceptor=netty
     [java] 	 ObjectName : jboss.as:subsystem=logging
     [java] 	 ObjectName : jboss.as:subsystem=jca
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=osgi-http
     [java] 	 ObjectName : jboss.as:subsystem=datasources
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.webapp
     [java] 	 ObjectName : jboss.jsr77:j2eeType=J2EEDomain,name=jboss.jsr77
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=jmx-connector-registry
     [java] 	 ObjectName : jboss.as:subsystem=security
     [java] 	 ObjectName : jboss.as:subsystem=jdr
     [java] 	 ObjectName : java.lang:type=ClassLoading
     [java] 	 ObjectName : jboss.as:subsystem=datasources,jdbc-driver=h2
     [java] 	 ObjectName : java.lang:type=Threading
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.logging
     [java] 	 ObjectName : jboss.as:subsystem=security,security-domain=jboss-web-policy
     [java] 	 ObjectName : jboss.as:subsystem=jmx
     [java] 	 ObjectName : jboss.as:subsystem=logging,logger=sun.rmi
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,jms-topic=testTopic
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,file-passivation-store=file
     [java] 	 ObjectName : jboss.as:deployment=Log4jDemo.war,subsystem=web,servlet=servlets.TestServlet
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=messaging-throughput
     [java] 	 ObjectName : jboss.as:subsystem=resource-adapters
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=management-http
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=https
     [java] 	 ObjectName : jboss.as:subsystem=jacorb
     [java] 	 ObjectName : jboss.as:core-service=service-container
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-acceptor=netty-throughput,param=direct-deliver
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.osgi
     [java] 	 ObjectName : jboss.jsr77:j2eeType=J2EEApplication,name=BeanValidation_EJB_Demo.ear,J2EEServer=default
     [java] 	 ObjectName : jboss.as:subsystem=remoting,connector=remoting-connector
     [java] 	 ObjectName : jboss.as:interface=public
     [java] 	 ObjectName : jboss.as:interface=management
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.jacorb
     [java] 	 ObjectName : java.lang:type=MemoryManager,name=CodeCacheManager
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.clustering.infinispan
     [java] 	 ObjectName : jboss.as:subsystem=ejb3,service=remote
     [java] 	 ObjectName : jboss.as:subsystem=weld
     [java] 	 ObjectName : jboss.as:deployment=Log4jDemo.war,subsystem=web
     [java] 	 ObjectName : jboss.jsr77:j2eeType=J2EEServer,name=default
     [java] 	 ObjectName : jboss.as:subsystem=logging,logger=com.arjuna
     [java] 	 ObjectName : jboss.as:subsystem=logging,root-logger=ROOT
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.apache.felix.webconsole
     [java] 	 ObjectName : jboss.as:deployment=MyDemoMDB.jar,subsystem=ejb3
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.cmp
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=local-query,singleton=eviction
     [java] 	 ObjectName : jboss.as:subsystem=remoting
     [java] 	 ObjectName : jboss.as:subsystem=logging,logger=jacorb.config
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=entity,singleton=expiration
     [java] 	 ObjectName : jboss.as:subsystem=web,virtual-server=default-host
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.deployment-scanner
     [java] 	 ObjectName : jboss.as:deployment=BeanValidation_EJB_Demo.ear,subdeployment=localEJB.jar,subsystem=ejb3
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.threads
     [java] 	 ObjectName : jboss.as:core-service=management,management-interface=http-interface
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.naming
     [java] 	 ObjectName : java.lang:type=OperatingSystem
     [java] 	 ObjectName : jboss.as:subsystem=osgi
     [java] 	 ObjectName : jboss.as:extension=org.jboss.as.jmx
     [java] 	 ObjectName : jboss.as:subsystem=messaging
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=org.jboss.osgi.jmx
     [java] 	 ObjectName : jboss.as:subsystem=infinispan,cache-container=hibernate,local-cache=timestamps
     [java] 	 ObjectName : jboss.as:deployment=TestWebApp.war,subsystem=web
     [java] 	 ObjectName : jboss.as:subsystem=osgi,capability=javax.api
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,connection-factory=InVmConnectionFactory
     [java] 	 ObjectName : jboss.as:socket-binding-group=standard-sockets,socket-binding=http
     [java] 	 ObjectName : jboss.as:subsystem=messaging,hornetq-server=default,remote-connector=netty
     [java] 	 ObjectName : jboss.as:subsystem=web
     [java] 	 ObjectName : jboss.as:subsystem=mail,mail-session=java%x3ajboss/mail/Default
     [java] 	 ObjectName : jboss.as:subsystem=jsr77
     [java] 	 ObjectName : jboss.as:subsystem=jmx,connector=jmx
     [java] 	 ObjectName : jboss.as:subsystem=web,configuration=container

BUILD SUCCESSFUL
Total time: 0 seconds

So like this we got all the list of MBean ObjectName present inside JBoss AS7.
.
.
Thanks :)
MiddlewareMagic Team


Getting WebService Statistics using JMX in JBoss AS7

Hi,

In this demonstration we will see how we can query the Statistics of a WebService deployed on JBoss using standard MBean code. In this example we will see that we need not to add any JAVA_OPTS in our JBoss configuration files in order to access these MBeans.

Here we will use a Sample webservice which will be deployed on JBoss AS7, for example you can refer to the following article to know how to deploy the WebService in JBoss: “http://middlewaremagic.com/jboss/?p=980” We will try to access the statistics of this webservice using our Standard JMX code. The statistics will include the following useful informations: “StartTime”, “StopTime”, “MinProcessingTime”, “AverageProcessingTime”, “MaxProcessingTime”, “RequestCount”..etc

JBoss side Configuration ( jboss-as-7.1.0.Beta1 )

Step1). Open the “/home/userone/jboss-as-7.1.0.Beta1/standalone/configuration/standalone-full.xml” file and edit the subsystem “urn:jboss:domain:jmx:1.1″ as following:

        <subsystem xmlns="urn:jboss:domain:jmx:1.1" show-model="true">
            <jmx-connector registry-binding="jmx-connector-registry" server-binding="jmx-connector-server"/>
        </subsystem>

Step2). Restart your JBoss Profile from “/home/userone/jboss-as-7.1.0.Beta1/bin” directory like following:

[userone@localhost bin]$ ./standalone.sh -c standalone-full.xml

Step3). Deploy your WebService on JBoss. For Testing you can use the webService mentioned in the following link:
http://middlewaremagic.com/jboss/?p=980

Step4). Now Somewhere in your filesystem write a Java Program “WebServiceMonitor.java” as following:

import java.util.Date;
import java.util.Hashtable;
import java.io.IOException;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.lang.management.MemoryMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;

public class WebServiceMonitor
{
    private static MBeanServerConnection connection;
    private static JMXConnector connector;
    public static void Connection(String hostname, String port) throws IOException
    {
        Integer portInteger = Integer.valueOf(port);
        Hashtable h = new Hashtable();
        JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+hostname+":"+port+"/jmxrmi");
        connector = JMXConnectorFactory.connect(address,null);
        connection = connector.getMBeanServerConnection();
        System.out.println("GOT THE MBeanServerConnection---SUCCESSFULLY");
    }

    private static void getServiceDetail(String contextRoot,String endPointName) throws Exception
    {
        ObjectName serviceRef=new ObjectName("jboss.ws:context="+contextRoot+",endpoint="+endPointName);
        String address=(String)connection.getAttribute(serviceRef, "Address");
        System.out.println("\t Address : "+address);
        Date startTime=(Date)connection.getAttribute(serviceRef, "StartTime");
        System.out.println("\t StartTime : "+startTime);
        Long minProcessingTime=(Long)connection.getAttribute(serviceRef, "MinProcessingTime");
        System.out.println("\t MinProcessingTime : "+minProcessingTime);
        Long maxProcessingTime=(Long)connection.getAttribute(serviceRef, "MaxProcessingTime");
        System.out.println("\t MaxProcessingTime : "+maxProcessingTime);
        Long totalProcessingTime=(Long)connection.getAttribute(serviceRef, "TotalProcessingTime");
        System.out.println("\t TotalProcessingTime : "+totalProcessingTime);
        Long requestCount=(Long)connection.getAttribute(serviceRef, "RequestCount");
        System.out.println("\t RequestCount : "+requestCount);
        Long responseCount=(Long)connection.getAttribute(serviceRef, "ResponseCount");
        System.out.println("\t ResponseCount : "+responseCount);
        Long faultCount=(Long)connection.getAttribute(serviceRef, "FaultCount");
        System.out.println("\t FaultCount : "+faultCount);
        Date stopTime=(Date)connection.getAttribute(serviceRef, "StopTime");
        System.out.println("\t StopTime : "+stopTime);
        Long averageProcessingTime=(Long)connection.getAttribute(serviceRef, "AverageProcessingTime");
        System.out.println("\t AverageProcessingTime : "+averageProcessingTime);
    }

    public static void main(String[] args) throws Exception
    {
    String hostname = args[0];
    String port = args[1];
    String contextRoot=args[2];
    String endPointName=args[3];
    Connection(hostname, port);
    System.out.println("------------------Getting Service Details------------------");
    System.out.println("jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS");
    System.out.println("-----------------------------------------------------------");
    getServiceDetail(contextRoot,endPointName);

    // ObjectName will be in the following format
    // "jboss.ws:context="+contextRoot+",endpoint="+endPointName
    //       Example:
    //       jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS
    }
}

Step5). Now we will write a simple Ant build script to build and execute the above program. So write an Ant build script “build.xml” file in the same directory where the above program is placed.

<project name="JBoss_Monitor" default="run">
<property name="jboss.home" value="/NotBackedUp/JBoss_All/jboss-as-7.1.0.Beta1" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="base.dir" value="." />

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

   <target name="run">
       <javac srcdir="${base.dir}" destdir="${base.dir}"  includes="WebServiceMonitor.java" classpathref="jboss.classpath"/>
       <java classname="WebServiceMonitor">
           <classpath>
              <pathelement location="${base.dir}"/>
              <path refid="jboss.classpath"/>
           </classpath>
           <arg line="localhost 1090  CXFTimeoutClientDemo Test_CXF_WS"/>
       </java>
   </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 is to point to your own JBoss AS7 directory home directory.

Step6). 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%

Step7). Run the command “ant” or “ant run” which will internally build the WebService and deploy it inside the JBoss AS7 standalone profile.

[userone@localhost Monitoring]$ ant run
Buildfile: /home/userone/Monitoring/build.xml

run:
     [java] GOT THE MBeanServerConnection---SUCCESSFULLY
     [java] ------------------Getting Service Details------------------
     [java] jboss.ws:context=CXFTimeoutClientDemo,endpoint=Test_CXF_WS
     [java] -----------------------------------------------------------
     [java] 	 Address : http://localhost:8080/CXFTimeoutClientDemo
     [java] 	 StartTime : Tue Nov 29 01:17:23 BTT 2011
     [java] 	 MinProcessingTime : 8
     [java] 	 MaxProcessingTime : 15191
     [java] 	 TotalProcessingTime : 15310
     [java] 	 RequestCount : 3
     [java] 	 ResponseCount : 3
     [java] 	 FaultCount : 0
     [java] 	 StopTime : null
     [java] 	 AverageProcessingTime : 5103

BUILD SUCCESSFUL
Total time: 2 seconds

Step8). If you want to run the above program manually then you will need to run the following command

.
java WebServiceMonitor localhost 1090 CXFTimeoutClientDemo Test_CXF_WS
.

NOTE: Here we are passing 4 Arguments
“localhost” (Here our JBoss is running),
“1090″ (This is the jmx-connector-registry connector port of JBoss which is enabled in the step1),
“CXFTimeoutClientDemo” (This is the Context Root of our WebService Application)
“Test_CXF_WS” (This is the Endpoint Name of our WebService)
.
.
.
Thanks
MiddlewareMagic Team


Listing & Deleting Messages from JMS Queue using JMX

Hi,

Many times due to different requirement it is desired to list all the Messages present inside the JMS Queue. Also some times it is required to delete all the messages present inside the JMS Queue. jmx-console can be used to perform the same tasks, but most of the time in production environments we disable the jmx-console or admin-console. So in such scenarios we can use the following kind of JMX code to list and if required then delete the Messages present inside the JMS Queue.

In this sample we will be using the default JMS Queue provided by JBoss as “queue/DLQ” but if you want to create your own JMS Queue then you can refer to the following article “How to create a Queue in JBoss ?“. Also we will be using a simple “QueueSend.java” program to send some test messages in the JMS Queue and then with the help of “ManageJMSQueue.java” program we will list the JMS Messages present inside the JMS Queue and if required we will delete them through the same JMX Code.

Step1). Write the Simple “QueueSend.java” program somewhere in your file system to send some JMS Messages to the JMS Queue “queue/DLQ” as following:

import java.io.*;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QueueSend
{
	public final static String JNDI_FACTORY="org.jnp.interfaces.NamingContextFactory";
	public final static String JMS_FACTORY="/XAConnectionFactory";
	public final static String QUEUE="/queue/DLQ";
	private QueueConnectionFactory qconFactory;
	private QueueConnection qcon;
	private QueueSession qsession;
	private QueueSender qsender;
	private Queue queue;
	private TextMessage msg;

public void init(Context ctx, String queueName)throws NamingException, JMSException
     {
	qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
	qcon = qconFactory.createQueueConnection();
	qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	queue = (Queue) ctx.lookup(queueName);
	qsender = qsession.createSender(queue);
	msg = qsession.createTextMessage();
	qcon.start();
     }

public void send(String message) throws JMSException
     {
	msg.setText(message);
	qsender.send(msg);
     }

public void close() throws JMSException
     {
	qsender.close();
	qsession.close();
	qcon.close();
     }

public static void main(String[] args) throws Exception {
	if (args.length != 1) {
	System.out.println("Usage: java QueueSend JBossURL");
	System.out.println("Example: java QueueSend localhost:1099");
	return;
	}
	InitialContext ic = getInitialContext(args[0]);
	QueueSend qs = new QueueSend();
	qs.init(ic, QUEUE);
	readAndSend(qs);
	qs.close();
	}

private static void readAndSend(QueueSend qs) throws IOException, JMSException
    {
	String line="Test Message Body with counter = ";
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	boolean readFlag=true;
	System.out.println("ntStart Sending Messages (Enter QUIT to Stop):n");
        int i=1;
	while(readFlag)
	{
	   System.out.print("<Msg_Sender> ");
	   String msg=br.readLine();
	   if(msg.equals("QUIT") || msg.equals("quit"))
	    {
	        qs.send(msg);
        	System.exit(0);
 	    }
        qs.send(msg);
        System.out.println("ttt msg sent: "+i+"t "+msg);
        i++;
        System.out.println();
	}
	br.close();
     }

private static InitialContext getInitialContext(String url) throws NamingException
    {
	Hashtable<String,String> env = new Hashtable<String,String>();
	env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
	env.put(Context.PROVIDER_URL, url);
	return new InitialContext(env);
    }
}

Step2). Now write the “ManageJMSQueue.java” program as following in order to list the messages present inside the JMS Queue “queue/DLQ” and if required delete them through the same code.

import javax.management.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import javax.naming.*;
import java.io.*;
public class ManageJMSQueue
   {
      private MBeanServerConnection server=null;
      public ManageJMSQueue()
      {
            try{
            Hashtable<String,String> ht=new Hashtable<String,String>();
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.security.jndi.JndiLoginInitialContextFactory");
            ht.put(Context.PROVIDER_URL,"localhost:1099");
            ht.put(Context.SECURITY_PRINCIPAL,"admin");
            ht.put(Context.SECURITY_CREDENTIALS,"admin");
            System.out.println("nt 1- Gotting InitialContext...... ");
            Context ctx = new InitialContext(ht);
            System.out.println("nt 2- Got InitialContext: "+ctx);
            server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor");
            }
            catch(Exception e)
            {
                System.out.println("nnt Exception inside ManageJMSQueue..."+e);
            }
      }

      public void monitorJMS() throws Exception
      {
           ObjectName objectName=new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue");
           System.out.println("nnServerPeer = "+ (javax.management.ObjectName)server.getAttribute(objectName, new String("ServerPeer")));
           System.out.println("QueueName = "+ (String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("Name")));
           System.out.println("JNDI Name = "+ (String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("JNDIName")));
           System.out.println("FullSize = "+ (Integer)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("FullSize")));
      }

     public void listAllJMS_Messages() throws Exception
      {
           ObjectName objectName=new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue");
           List<org.jboss.jms.message.JBossTextMessage> messages=(List<org.jboss.jms.message.JBossTextMessage>)server.invoke(objectName, "listAllMessages" , null, null);
           int count=0;
           for(org.jboss.jms.message.JBossTextMessage msg : messages)
                    System.out.println((++count)+"t"+msg.getText());
      }

     public void removeAllJMS_Messages() throws Exception
      {
           String queueName=(String)server.getAttribute(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), new String("Name"));
           System.out.println("nt Removing all JMS Messages from Queue: "+queueName);
           server.invoke(new ObjectName("jboss.messaging.destination:name=DLQ,service=Queue"), "removeAllMessages" , null, null);
           System.out.println("nt All the Messages are removed from JMS Queue: "+queueName);
      }

     public static void main(String ar[]) throws Exception
       {
            ManageJMSQueue ref=new ManageJMSQueue();
            ref.monitorJMS();
            System.out.println("nt Following Messages Are present inside the JMS Queue:");
            ref.listAllJMS_Messages();
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("nn Please Specify (yes/no) to delete all the messages from JMS Queue ? ");
            String answer="";
            if((answer=br.readLine()).equals("yes"))
                             ref.removeAllJMS_Messages();
            br.close();
       }
  }

Step3). Compile and then run the “QueueSend.java” program as following and then send some messages to the JMS Queue:

javac QueueSend.java
java QueueSend localhost:1099
	Start Sending Messages (Enter QUIT to Stop):

<Msg_Sender> TestMessageOne
			 msg sent: 1	 TestMessageOne

<Msg_Sender> TestMessageTwo
			 msg sent: 2	 TestMessageTwo

<Msg_Sender> TestMessageThree
			 msg sent: 3	 TestMessageThree

<Msg_Sender> quit

Step4). After sending some Messages to the JMS Queue “queue/DLQ” Compile and then run the “ManageJMSQueue” program as following to list the messages present inside the JMS Queue:

javac ManageJMSQueue.java
java ManageJMSQueue localhost:1099

	 1- Gotting InitialContext......
	 2- Got InitialContext: javax.naming.InitialContext@74341960

ServerPeer = jboss.messaging:service=ServerPeer
QueueName = DLQ
JNDI Name = /queue/DLQ
FullSize = 200000

	 Following Messages Are present inside the JMS Queue:
1	TestMessageOne
2	TestMessageTwo
3	TestMessageThree
4	quit

 Please Specify (yes/no) toi delete all the messages from JMS Queue ? yes
	 Removing all JMS Messages from Queue: DLQ
	 All the Messages are removed from JMS Queue: DLQ

.
.
Thanks
Middleware Magic Team


Monitoring Heap & NonHeap Memory of JBoss using MBean code

Hi,

If we want to analyse the Heap & Non-Heap Usages of JBoss Application Server’s JVM remotely then we can use JConsole, Visual JVM etc. Apart from these utilities we can also use the following Simple JMX Code.

You can enhance this tiny code to Develop your own Mini/Light weight class where you can add your Java Mail API code to send an automated alert to the Administrator as soon as the monitoring statistics becomes abnormal or to perform some activities like collecting Thread dumps etc.

To connect to the actual JConsole remotely also we need to provide the following JAVA_OPTS inside our “$JBOSS_HOME/bin/run.conf” or inside “$PROFILE/run.conf” file (NOTE: for windows machines we can add this JAVA_OPTS inside “%JBOSS_HOME/bin/run.conf.bat” or “%PROFILE%/run.conf.bat”) and the connection url format should be:

service:jmx:rmi:///jndi/rmi://"+hostname+":"+port+"/jmxrmi

Step1). Edit the “%JBOSS_HOME%/bin/run.conf.bat” or “%JBOSS_HOME%/bin/run.bat” (Server StartScript configuration file) and then set the following JAVA_OPTS there.

set JAVA_OPTS="%JAVA_OPTS% -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.port=4545 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl -Djboss.platform.mbeanserver"

For Unix Based Operating System edit the “$JBOSS_HOME/bin/run.conf” OR “$JBOSS_HOME/bin/run.sh” OR “$PROFILE/run.conf” file as following:

JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.port=4545 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl -Djboss.platform.mbeanserver"

Make sure that the 4545 is not being used by any other process. Or define any other port in above parameter which is free.

Step2). Now from any other box or from the same Box you can run the Following JMX code to get Heap & Non Heap Usages of the JVM:
“HeapAndNonHeapMonitoring.java”

import java.util.Hashtable;
import java.io.*;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import java.lang.management.MemoryMXBean;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.management.*;
import javax.management.openmbean.CompositeDataSupport;

public class HeapAndNonHeapMonitoring
{
	private static MBeanServerConnection connection;
	private static JMXConnector connector;
public static void Connection(String hostname, String port) throws IOException
	{
	Integer portInteger = Integer.valueOf(port);
	Hashtable h = new Hashtable();
	JMXServiceURL address = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://"+hostname+":"+port+"/jmxrmi");
	connector = JMXConnectorFactory.connect(address,null);
	connection = connector.getMBeanServerConnection();
	System.out.println("GOT THE MBeanServerConnection---SUCCESSFULLY");
	}

private static void doGarbageCollection() throws Exception
{
	ObjectName memoryMXBean=new ObjectName("java.lang:type=Memory");
	connection.invoke(memoryMXBean,"gc", null, null);
	System.out.println("nnt------Garbage Collection Done Successfully-----");
}

private static void doOperatingSystemDetails() throws Exception
{
	ObjectName operatingSystemMXBean=new ObjectName("java.lang:type=OperatingSystem");
	Object systemLoadAverage = connection.getAttribute(operatingSystemMXBean, "SystemLoadAverage");

	Long freePhysicalMemory = (Long) connection.getAttribute(operatingSystemMXBean, "FreePhysicalMemorySize");
	Long processCpuTime = (Long) connection.getAttribute(operatingSystemMXBean, "ProcessCpuTime");
	Long committedVirtualMemorySize = (Long) connection.getAttribute(operatingSystemMXBean, "CommittedVirtualMemorySize");
	Long freeSwapSpaceSize = (Long) connection.getAttribute(operatingSystemMXBean, "FreeSwapSpaceSize");
	Long totalPhysicalMemorySize = (Long) connection.getAttribute(operatingSystemMXBean, "TotalPhysicalMemorySize");
	Long totalSwapSpaceSize = (Long) connection.getAttribute(operatingSystemMXBean, "TotalSwapSpaceSize");

	System.out.println("Operating SystemLoadAverage: " + systemLoadAverage);
	System.out.println("Operating System FreePhysicalMemory: " + (freePhysicalMemory/(1024*1024))+"-MB");
	System.out.println("Operating System processCpuTime: " + processCpuTime);
	System.out.println("Operating System committedVirtualMemorySize: " + (committedVirtualMemorySize/(1024*1024))+"-MB");
	System.out.println("Operating System freeSwapSpaceSize: " + (freeSwapSpaceSize/(1024*1024))+"-MB");
	System.out.println("Operating System totalPhysicalMemorySize: " + (totalPhysicalMemorySize/(1024*1024))+"-MB");
	System.out.println("Operating System totalSwapSpaceSize: " + (totalSwapSpaceSize/(1024*1024))+"-MB");
}

private static void getHeapMemoryUsage() throws Exception
{
	ObjectName memoryMXBean=new ObjectName("java.lang:type=Memory");
	CompositeDataSupport dataSenders = (CompositeDataSupport) connection.getAttribute(memoryMXBean,"HeapMemoryUsage");
	if (dataSenders != null)
	  {
		Long commited = (Long) dataSenders.get("committed");
		Long init = (Long) dataSenders.get("init");
		Long max = (Long) dataSenders.get("max");
		Long used = (Long) dataSenders.get("used");
		Long percentage = ((used * 100) / max);
		System.out.println("nnt commited   : "+commited/(1024*1024)+" MB");
		System.out.println("t init       : "+init/(1024*1024)+" MB");
		System.out.println("t max        : "+max/(1024*1024)+" MB");
		System.out.println("t used       : "+used/(1024*1024)+" MB");
		System.out.println("t percentage : "+percentage +" %");
	   }
}

private static void getNonHeapMemoryUsage() throws Exception
{
	ObjectName memoryMXBean=new ObjectName("java.lang:type=Memory");
	CompositeDataSupport dataSenders = (CompositeDataSupport) connection.getAttribute(memoryMXBean,"NonHeapMemoryUsage");
	if (dataSenders != null)
	{
		Long commited = (Long) dataSenders.get("committed");
		Long init = (Long) dataSenders.get("init");
		Long max = (Long) dataSenders.get("max");
		Long used = (Long) dataSenders.get("used");
		Long percentage = ((used * 100) / max);
		System.out.println("nnt commited   : "+commited/(1024*1024)+" MB");
		System.out.println("t init       : "+init/(1024*1024)+" MB");
		System.out.println("t max        : "+max/(1024*1024)+" MB");
		System.out.println("t used       : "+used/(1024*1024)+" MB");
		System.out.println("t percentage : "+percentage +" %");
	}
}

public static void main(String[] args) throws Exception
     {
	String hostname = args[0];
	String port = args[1];
	Connection(hostname, port);
	//doGarbageCollection();                // --&gt; use this method if you want to perform Garbage Collection
	System.out.println("nt----------HEAP Memory Usages---------");
	getHeapMemoryUsage();
	System.out.println("nt----------Non-HEAP Memory Usages---------");
	getNonHeapMemoryUsage();
	System.out.println("nt----------Operating System Usages---------");
	doOperatingSystemDetails();
	connector.close();
     }
}

Step3). Compile and run the above program as following:

javac  HeapAndNonHeapMonitoring.java
java  HeapAndNonHeapMonitoring  10.10.10.10  4545

Here 10.10.10.10 is the JBoss Server Listen Address.
4545 is the port -Dcom.sun.management.jmxremote.port defined in the JAVA_OPTS

OUTPUT:

java HeapAndNonHeapMonitoring localhost 4545
GOT THE MBeanServerConnection---SUCCESSFULLY

	----------HEAP Memory Usages---------
	 commited   : 384 MB
	 init       : 58 MB
	 max        : 837 MB
	 used       : 344 MB
	 percentage : 41 %

	----------Non-HEAP Memory Usages---------
	 commited   : 79 MB
	 init       : 23 MB
	 max        : 214 MB
	 used       : 75 MB
	 percentage : 35 %

	----------Operating System Usages---------
	Operating System LoadAverage: 0.38
	Operating System FreePhysicalMemory: 650-MB
	Operating System processCpuTime: 54850000000
	Operating System committedVirtualMemorySize: 3396-MB
	Operating System freeSwapSpaceSize: 5813-MB
	Operating System totalPhysicalMemorySize: 3760-MB
	Operating System totalSwapSpaceSize: 5823-MB

NOTE: Do not start your JBoss instance on bind address 0.0.0.0 which creates problem while RMI communication.

.
.
Thanks
Middleware Magic Team


  • Receive FREE Updates


    FREE Email updates of our new posts Enter your email address:



  • Magic Archives

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