Tag: MBeans

SAR dependency alternate approach using @Singleton in JBossAS7.1.2

Hi,

SAR files are called as Service Archives. The extension of SAR files are *.sar which contains a “META-INF/jboss-service.xml” file, this file describes the custom MBeans which has to be exposed at the time of deployment or JBoss Startup. JBoss’s service archive architecture is based on the JMX and the SAR files which are basically JBoss specific can be deployed in the jboss inorder to publish your MBean based services. At the time of JBoss startup these service archive deployer (SARDeployer) instantiates the JBoss service classes and exposes them as manageable beans through JMX.

In previous release of JBoss 5/6 the SAR provided mbeans dependency could be very easily defined using <depends> tag, as following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server>
<server>
    <mbean code="custom.mbean.MyServerMonitor" name="service.server.monitor:service=MyMonitor">
         <attribute name="Frequency">5000</attribute>
         <depends>jboss.jca:service=DataSourceBinding,name=MySqlDS</depends>
    </mbean>
</server>

@org.jboss.ejb3.annotation.Service and @org.jboss.ejb3.annotation.Management are no longer supported which could be used to define Services. However in JBossAS7 this approach of defining the dependency is not good and you may see following kind of exceptions at the time of server startup:

JBAS014775:    New missing/unsatisfied dependencies:
      service jboss.mbean.service."jboss.as:subsystem=datasources,data-source=MySqlDS".create (missing) dependents: [service jboss.mbean.service."service.server.monitor:service=MyMonitor".create]
      service jboss.mbean.service."jboss.as:subsystem=datasources,data-source=MySqlDS".start (missing) dependents: [service jboss.mbean.service."service.server.monitor:service=MyMonitor".start]

JBossAS7 is fully EE6 certified application server and it provides a much better approach to create a Service with the help of EJB3.1 specific “javax.ejb.Startup” and “javax.ejb.Singleton” annotations. This kind of service can be made dependent to other services like DataSource. In this example we will see What is the better approach to define a service (without using container specific SAR feature).

The Source code for this demo can be found in the following github link:
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/SingletonServiceDemo

Creating DataSource in JBossAS7.1.2

As we are going make our Service dependent on a DataSource, sothat we can see how the dependency goes.

Configuration-1). So here first of all we will create a DataSource by running the following CLI script in batch mode. So create a file with name “createDataSource.cli” somewhere in your filesystem like “/home/jaysensharma/SingletonServiceDemo/createDataSource.cli” as following:

deploy  /home/jaysensharma/SingletonServiceDemo/mysql-connector-java-5.1.13-bin.jar

/subsystem=datasources/data-source="MySqlDS":add(jndi-name="java:jboss/datasources/MySqlDS",driver-name="mysql-connector-java-5.1.13-bin.jar",connection-url="jdbc:mysql://localhost:3306/testDB",user-name="root",password="redhat")

Configuration-2). Now start your “$JBOSS_HOME/bin/jboss-cli.sh” script in order to run the above deploy the mysql driver and create DataSource as following:

./jboss-cli.sh -c --controller=10.10.10.10:9999 --file=/home/jaysensharma/SingletonServiceDemo/createDataSource.cli

Configuration-3). As soon as you will run the cli script as mentioned above you will see that the following kind of datasource is created on your standalone*.xml.

                <datasource jndi-name="java:jboss/datasources/MySqlDS" pool-name="MySqlDS">
                    <connection-url>jdbc:mysql://localhost:3306/testDB</connection-url>
                    <driver>mysql-connector-java-5.1.13-bin.jar</driver>
                    <security>
                        <user-name>root</user-name>
                        <password>redhat</password>
                    </security>
                </datasource>

Creating @Singleton service dependent on the DataSource

Step1). First of all we will create a directory somewhere in our file system as “/home/jaysensharma/SingletonServiceDemo” and then we will create a directory with name “src” inside “/home/jaysensharma/SingletonServiceDemo”:

Step2). Now write a @Startup @Singleton EJB3.1 service using “SingletonServiceBean.java” inside “/home/jaysensharma/SingletonServiceDemo/src” as following:

package sar.dependency.alternative;
import javax.ejb.Startup;
import javax.ejb.Singleton;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

//commons logging
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

// DataSource related
import javax.sql.DataSource;
import java.sql.Connection;

// Resource Injection related
import javax.annotation.Resource;

@Startup
@Singleton  

public class SingletonServiceBean
 {
     private static Log logger = LogFactory.getLog(SingletonServiceBean.class);
     Connection con=null;

     public SingletonServiceBean()
            {
               logger.info("SingletonServiceBean constructor invoked.");
            }

     @Resource(name = "java:jboss/datasources/MySqlDS")
     DataSource ds;
     /* This @PostConstruct annotation is required to tell JBoss to invoke the "performOperations" immediately after the "SingletonServiceBean" creation. */
     @PostConstruct
     public void performOperations()
	    {
               logger.info("SingletonServiceBean performOperations() invoked.");
               try{
                     con=ds.getConnection();
                     logger.info("***** DataSource = "+ds+" . Connection con = "+con+" retrieved from the ConnectionPool.*****");
                  }
               catch(Exception e)
                 {
                     logger.error("Unable to get Connection From DataSource = "+ds+" ERROR: "+e.getMessage());
                     e.printStackTrace();
                 }
	    }

	@PreDestroy
	public void cleanUp() throws Exception {
	  logger.info("cleaning up connections.");
          if(con!=null)
            {
               try{
                     con.close();
                     logger.info("Connection con = "+con+" is successfully returned to the ConnectionPool.");
                  }
               catch(Exception e)
                 {
                     logger.error("Unable to Close Connection con = "+con+" ERROR: "+e.getMessage());
                     e.printStackTrace();
                 }
               finally{
                        try{   con.close(); }
                        catch(Exception ee) { ee.printStackTrace(); }
                      }
            }
	}
 }

Step3). Now the most important part of building / deploying the Singleton Service which we created, so in order to achieve that we will create a simple ant build script, So Create a “build.xml” file inside the “/home/jaysensharma/SingletonServiceDemo” directory as following:

<project name="SingletonStartupService" default="all">
<property name="jboss.home" value="/home/jaysensharma/jboss-as-7.1.2.Final" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="src.dir" value="src" />
<property name="output.dir" value="build" />
<property name="ear.name" value="TestSingletonService.ear" />
<property name="ejb.jar" value="singletonServiceEJB.jar" />

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

        <target name="all" depends="deploy" />

        <target name="build_ear">
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <javac srcdir="${src.dir}" destdir="${tmp.dir}"  includes="*.java" classpathref="jboss.classpath"/>

           <jar jarfile="${tmp.dir}/${ejb.jar}" basedir="${tmp.dir}" compress="true" />

           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}/sar"/>
           </delete>
           <mkdir dir="${tmp.dir}/META-INF"/>
           <copy todir="${tmp.dir}/META-INF">
                <fileset dir="${src.dir}/">
                  <include name="application.xml"/>
                </fileset>
           </copy>
           <jar jarfile="${tmp.dir}/${ear.name}" basedir="${tmp.dir}" compress="true" />
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}/META-INF"/>
           </delete>
           <delete file="${tmp.dir}/${ejb.jar}"/>

           <copy file="${tmp.dir}/${ear.name}" tofile="${output.dir}/${ear.name}"/>
           <delete dir="${tmp.dir}"/>
        </target>

        <target name="deploy" depends="build_ear">
            <echo message="*******************  Deploying the EAR file ${ear.name} *********************" />
            <echo message="********** ${output.dir}/${ear.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${ear.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-4). 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/jaysensharma/jdk1.6.0_21/bin:/home/jaysensharma/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-5). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/jaysensharma/SingletonServiceDemo” and then run the ant to build and deploy the EJB based EAR applicationon your JBoss Standalone full profile, by running the command “ant deploy”

[jaysensharma@localhost SingletonServiceDemo]$ ant
Buildfile: build.xml

build_ear:
    [mkdir] Created dir: /home/jaysensharma/SingletonServiceDemo/tmp
    [javac] Compiling 1 source file to /home/jaysensharma/SingletonServiceDemo/tmp
      [jar] Building jar: /home/jaysensharma/SingletonServiceDemo/tmp/singletonServiceEJB.jar
    [mkdir] Created dir: /home/jaysensharma/SingletonServiceDemo/tmp/META-INF
      [jar] Building jar: /home/jaysensharma/SingletonServiceDemo/tmp/TestSingletonService.ear
   [delete] Deleting: /home/jaysensharma/SingletonServiceDemo/tmp/singletonServiceEJB.jar
     [copy] Copying 1 file to /home/jaysensharma/SingletonServiceDemo/build
   [delete] Deleting directory /home/jaysensharma/SingletonServiceDemo/tmp

deploy:
     [echo] *******************  Deploying the EAR file TestSingletonService.ear *********************
     [echo] ********** build/TestSingletonService.ear to /home/jaysensharma/jboss-as-7.1.2.Final/standalone/deployments **********
     [copy] Copying 1 file to /home/jaysensharma/jboss-as-7.1.2.Final/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

all:

BUILD SUCCESSFUL
Total time: 1 second

Step-6). As the application is deployed on your JBoss so now try restarting your JBoss and then see whether the Above service us successfully get the DataSource and JDBC Connection or not. If the Dependency is correctly working then after restarting your JBoss you will see the following kind of message on your JBoss console / logs.

22:41:51,569 INFO  [sar.dependency.alternative.SingletonServiceBean] (MSC service thread 1-1) ***** DataSource = org.jboss.jca.adapters.jdbc.WrapperDataSource@43877c42 . Connection con = org.jboss.jca.adapters.jdbc.jdk6.WrappedConnectionJDK6@5424bf0 retrieved from the ConnectionPool.*****

.
.
Thanks
MiddlewareMagic Team :)


How to get All Cluster Node Details using JMX in JBossAS7.1.2

Hi,

In JBoss EAP5 or AS6 or previous releases there was a concept of Partition Name which could be used to get the list of active cluster members, However in JBoss AS7 there is no concept of PartitionName rather in UDP mode the lustering happens based on the multicast asddress (Clustering can be achieved using TCP mode of communication as well). However many developers want to list the number of active members running as part of a JBoss As7 cluster programatically.

So in this example we will see how to write a simple JMX Code in order to access the cluster node details.

NOTE:

Point-1) . In JBoss AS7 until you deploy an application which requires clustering the JBoss will now start the clustering services. So in case of web Applications you should deploy at least one application on your Cluster members which has <distributable/> tag specified in it’s “WEB-INF/web.xml” file.

Point-2) . If you are using EJBs (and not web application to deploy on your cluster) make sure that the EJBs are clustered in order to start Cluster services. EJBs can be annotated using the following annotation in order to be clustered. @org.jboss.ejb3.annotation.Clustered

Point-3) . In Case of WebBased cluster the ObjectName of the Clustered instance will be “jgroups:type=channel,cluster=web” by default which can be used in the JMX Code in order to look query the MBean.

Point-3) . In Case of EJBBased cluster the ObjectName of the Clustered instance will be “jgroups:type=channel,cluster=ejb” by default which can be used in the JMX Code in order to look query the MBean.

Point-5) . If you are running your Server in Domain Mode then you should not use the Native Management Port 9999 in order to query the MBeans rather you should use the individual server’s Remoting Port 4447 in your JMX Code. by adding the following configuration on your JBoss Profile inside domain.xml you can allow accessing the MBeans via Remoting port 4447 rather than (native management port 9999)

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

Point-6) . If you are using Native Management Interface port 9999 in order to query your Cluster MBean (in standalone mode) then you should use the Credentials (username/password) for a user belonging to ManagementRealm, But in Domain mode as we need to connect to server using Remoting Port (4447) so you should create a ApplicationRealm user. in all the cluster Hosts.

Writing the JMX codce to query Cluster MBean

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

public class AS7ClusterView {
	public static void main(String[] args) throws Exception {

		String host = "10.10.10.10"; // Your JBoss Native Interface Bin Address default is localhost
		int port = 9999;             // management port     // In Domain Mode you should use  4447 port of individual server
		String urlString = "service:jmx:remoting-jmx://" + host + ":" + port;
		System.out.println(" \n\n\t**** urlString: " + urlString);
                String webClusterObjectName="jgroups:type=channel,cluster=\"web\"";
                //String ejbClusterObjectName="jgroups:type=channel,cluster=\"ejb\"";

		JMXServiceURL serviceURL = new JMXServiceURL(urlString);

		Hashtable h = new Hashtable();
		String[] credentials = new String[] { "admin", "admin123" };
		h.put("jmx.remote.credentials", credentials);

		JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL,null);
		MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
		ObjectName objectName = new ObjectName(webClusterObjectName);
		String clusterView = (String) connection.getAttribute(objectName,"View");
		Long receivedMessages = (Long) connection.getAttribute(objectName,"ReceivedMessages");
		String name = (String) connection.getAttribute(objectName, "Name");
		String clusterName = (String) connection.getAttribute(objectName,"ClusterName");

		System.out.println(" clusterView = " + clusterView);
		System.out.println(" receivedMessages = " + receivedMessages);
		System.out.println(" name = " + name);
		System.out.println(" clusterName = " + clusterName);
		jmxConnector.close();
	}

}

Now open a Terminal where we need to set the PATh and CLASSPATH like following and then compile and run the program:

For UNIX Based Operating System:

export PATH=/home/userone/jdk1.6.0_21/bin:$PATH
export CLASSPATH=/home/userone/jboss-as-7.1.2.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.2.Final\bin\client\jboss-client.jar;%CLASSPATH%;.;

.
.
Thanks :)
MiddlewareMagic Team


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


How to create a Service Archieve SAR file in JBoss AS7

Hi,

SAR files are called as Service Archives. The extension of SAR files are *.sar which contains a “META-INF/jboss-service.xml” file, this file describes the custom MBeans which has to be exposed at the time of deployment or JBoss Startup. JBoss’s service archive architecture is based on the JMX and the SAR files which are basically JBoss specific can be deployed in the jboss inorder to publish your MBean based services. At the time of JBoss startup these service archive deployer (SARDeployer) instantiates the JBoss service classes and exposes them as manageable beans through JMX. These beans can be viewed and edited from the jmx-console as well.

You can refer to the sample of creating service archives in JBoss AS6 in the following link: http://middlewaremagic.com/jboss/?p=307 .

But in JBoss AS 7 it is little different as the class “org.jboss.system.ServiceMBean” and “org.jboss.system.ServiceMBeanSupport” are not present in JBoss AS7. Also the JBoss AS 7 service descriptor (jboss-service.xml) file requires XSD declaration, And without the XSD declaration inside jboss-service.xml file you will see the following kind of Exception while deploying your SAR file.

23:10:52,007 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC00001: Failed to start service jboss.deployment.unit."ServerMonitorService.sar".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."ServerMonitorService.sar".PARSE: Failed to process phase PARSE of deployment "ServerMonitorService.sar"
	at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:121)
	at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1765)
	at org.jboss.msc.service.ServiceControllerImpl$ClearTCCLTask.run(ServiceControllerImpl.java:2291)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [:1.6.0_21]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [:1.6.0_21]
	at java.lang.Thread.run(Thread.java:619) [:1.6.0_21]
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: Failed to parse service xml ["/home/userone/jboss-as-7.0.1.Final/standalone/deployments/ServerMonitorService.sar/META-INF/jboss-service.xml"]
	at org.jboss.as.service.ServiceDeploymentParsingProcessor.deploy(ServiceDeploymentParsingProcessor.java:94)
	at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:115)
	... 5 more
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[3,1]
Message: Unexpected element 'server'
	at org.jboss.staxmapper.XMLMapperImpl.processNested(XMLMapperImpl.java:98)
	at org.jboss.staxmapper.XMLMapperImpl.parseDocument(XMLMapperImpl.java:59)
	at org.jboss.as.service.ServiceDeploymentParsingProcessor.deploy(ServiceDeploymentParsingProcessor.java:87)

Also in JBoss AS7 we need to implement the start() and stop() service if we want to perform some specific operations while jboss starts and stops the service. So here we will try to develop a Service Archive in this sample.

Step1). Create a directory somewhere in your file system like “/home/userone/ServerMonitorService.sar”.

Step2). Create an MBean interface “MyServerMonitorMBean.java” inside the “/home/userone/ServerMonitorService.sar” directory.

package custom.mbean;
public interface MyServerMonitorMBean
  {
      public void setFrequency(String frequency);
      public String getFrequency();
  }

Step3). Now provide an implementation class of the above MBean interface as “MyServerMonitor.java” inside the directory “/home/userone/ServerMonitorService.sar”. And implement the start() and stop() service if we want to perform some specific operations while jboss starts and stops the service.

package custom.mbean;
import javax.management.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import javax.naming.*;
public class MyServerMonitor implements MyServerMonitorMBean
  {
      boolean flag=true;
      public String Frequency;

      public MyServerMonitor()
      {
         System.out.println("nnt ServiceMonitorMBean is activated...inside ServiceMonitor() constructor--setting default Frequency=10000 Miliseconds");;
      }

      public void setFrequency(String Frequency)
      {
          System.out.println("nt Server Watch Frequency is set to : "+Frequency+"-Milliseconds");
          this.Frequency=Frequency;
      }

      public String getFrequency()
      {
          System.out.println("nt Server Watch Frequency is set to : "+Frequency+"-Milliseconds");
          return this.Frequency;
      }

     public void start() throws Exception
      {
            System.out.println("nntStarting start() MyServerMonitor invoked");
            Frequency="3000";
      }

     public void stop() throws Exception
      {
            System.out.println("nntStopping stop() MyServerMonitor  invoked");
      }
  }

Now compile the above Codes as following

cd   /home/userone/ServerMonitorService.sar/
javac   -d   .   *.java

Step4). Now the most important part, here we need to declare the MBean inside the “/home/userone/ServerMonitorService.sar/META-INF/jboss-service.xml” file as following:

<?xml version="1.0" encoding="UTF-8"?>
<server xmlns="urn:jboss:service:7.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:jboss:service:7.0 jboss-service_7_0.xsd">

    <mbean code="custom.mbean.MyServerMonitor" name="service.server.monitor:service=MyMonitor">
         <attribute name="Frequency">5000</attribute>
    </mbean>

</server>

NOTE: The XSD declaration is required without that you will see parsing error while deploying your service.

Step5). Deploy the “ServerMonitorService.sar” inside the “jboss-as-7.0.1.Final/standalone/deployments” directory of your JBoss. After deploying the service archive you may see the following Message in server’s Console Stdout….Because the “ServerMonitorService.sar” which we are trying to deploy is in Exploded format:

23:19:17,410 INFO  [org.jboss.as.deployment] (DeploymentScanner-threads - 1) Found ServerMonitorService.sar in deployment directory. To trigger deployment create a file called ServerMonitorService.sar.dodeploy

Step6). So create an empty file with name “ServerMonitorService.sar.dodeploy” inside “jboss-as-7.0.1.Final/standalone/deployments” to tell jboss to deploy this Service Archive.

NOTE: If you don’t want to see the message which is displayed in Step5) and don’t want to follow Step6).. then deploy your SAR file as an archive file. (similar to how we create jar/war/ear files using jar utility)

JIRA related to current demonstration: https://issues.jboss.org/browse/AS7-887
.
.
Thanks
Middleware Magic Team


How to create a Service Archieve SAR file in JBoss AS6

Hi,
NOTE: this article is focused on JBoss AS6 and earlier versions. For JBoss AS7 service archives please refer to: http://middlewaremagic.com/jboss/?p=366

SAR files are called as Service Archives. The extension of SAR files are *.sar which contains a “META-INF/jboss-service.xml” file, this file describes the custom MBeans which has to be exposed at the time of deployment or JBoss Startup. JBoss’s service archive architecture is based on the JMX and the SAR files which are basically JBoss specific can be deployed in the jboss inorder to publish your MBean based services. At the time of JBoss startup these service archive deployer (SARDeployer) instantiates the JBoss service classes and exposes them as manageable beans through JMX. These beans can be viewed and edited from the jmx-console as well.

One of the best usage of the service archieve is to monitor the servers activities. In this simple example we will try to get JBoss Server’s basic informations using the JBoss MBean “jboss.system:type=Server” using our SAR file.

Step1). Create a directory somewhere in your file system like “/home/userone/ServerMonitorService.sar”.

Step2). Create an MBean interface by extending the interface “org.jboss.system.ServiceMBean” as following. “MyServerMonitorMBean.java” inside the “/home/userone/ServerMonitorService.sar” directory.

package custom.mbean;
import org.jboss.system.ServiceMBean;
public interface MyServerMonitorMBean extends org.jboss.system.ServiceMBean
  {
      public void setFrequency(String frequency);
      public String getFrequency();
  }

Step3). Now provide an implementation class of the above MBean interface as “MyServerMonitor.java” inside the directory “/home/userone/ServerMonitorService.sar”. Make sure that this class extends the “org.jboss.system.ServiceMBeanSupport” class because this class provides some useful methods like “startService()” and “stopService()” which are the life cycle methids of our beans.

package custom.mbean;
import javax.management.*;
import java.io.*;
import java.util.*;
import java.rmi.*;
import javax.naming.*;
public class MyServerMonitor extends org.jboss.system.ServiceMBeanSupport implements MyServerMonitorMBean
  {
      boolean flag=true;
      public String Frequency;
      private MBeanServerConnection server=null;
      public void setFrequency(String Frequency)
      {
          System.out.println("nt Server Watch Frequency is set to : "+Frequency+"-Milliseconds");
          this.Frequency=Frequency;
      }
      public String getFrequency()
      {
          System.out.println("nt Server Watch Frequency is set to : "+Frequency+"-Milliseconds");
          return this.Frequency;
      }
      public MyServerMonitor()
      {
         System.out.println("nnt ServiceMonitorMBean is activated...inside ServiceMonitor() constructor--setting default Frequency=10000 Miliseconds");;
      }

     public void startService() throws Exception
      {
         log.info("nntStarting MyServerMonitor");
            try{
            Hashtable ht=new Hashtable();
            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 MyServerMonitor..."+e);
            }
            Frequency="5000";
            ServerMonitorRunner runner=new ServerMonitorRunner();
      }

      public void monitor() throws Exception
      {
            String data="";
            data=data+"nnt===================MyServerMonitor.monitor()===================";
            data=data+"nBuildOS = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildOS"));
            data=data+"nVersionName = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("VersionName"));
            data=data+"nBuildDate = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildDate"));
            data=data+"nInShutdown = "+ (Boolean)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("InShutdown"));
            data=data+"nStartDate = "+ (java.util.Date)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("StartDate"));
            data=data+"nStarted = "+ (Boolean)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("Started"));
            data=data+"nBuildNumber = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildNumber"));
            data=data+"nBuildJVM = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("BuildJVM"));
            data=data+"nVersionNumber = "+ (String)server.getAttribute(new ObjectName("jboss.system:type=Server"), new String("VersionNumber"));
            data=data+"nt===============================================================";
            System.out.println(data);
      }

     public void stopService() throws Exception
      {
         log.info("nntStopping MyServerMonitor");
      }
     class ServerMonitorRunner extends Thread
       {
           ServerMonitorRunner()
            {
                this.start();
            }
           public void run()
             {
                for(; ;)
                  {
                    try{
                          Thread.sleep(Integer.parseInt(Frequency));
                          monitor();
                       }
                    catch(InterruptedException ie){ ie.printStackTrace();}
                    catch(Exception e){ e.printStackTrace();}

                  }
             }
       }
  }

Step4). Now the most important part, here we need to declare the MBean inside the “/home/userone/ServerMonitorService.sar/META-INF/jboss-service.xml” file as following:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE server>
<server>
    <mbean code="custom.mbean.MyServerMonitor" name="service.server.monitor:service=MyMonitor">
         <attribute name="Frequency">5000</attribute>
         <depends>jboss.jmx:type=adaptor,name=Invoker,protocol=jrmp,service=proxyFactory</depends>
    </mbean>
</server>

NOTE: here inside the tag we have used the tag because our MBean is dependent on another MBean “jboss.jmx:type=adaptor,name=Invoker,protocol=jrmp,service=proxyFactory”…this is why because our MBean code is performing ic.lookup() using the “jmx/invoker/RMIAdaptor” so we need to make sure that the “jboss.jmx:type=adaptor,name=Invoker,protocol=jrmp,service=proxyFactory” service gets activated before our MBean. otherwise we will see NullPointerException while performing lookup inside our bean.

Step5). Deploy the “ServerMonitorService.sar” inside the “${PROFILE}/deploy” directory of your JBoss. And then you will start seeing the following kind of messages in the server Console :

12:55:53,949 INFO  [STDOUT]
	 ServiceMonitorMBean is activated...inside ServiceMonitor() constructor--setting default Frequency=10000 Miliseconds
12:55:53,952 INFO  [STDOUT]
	 Server Watch Frequency is set to : 5000-Milliseconds
12:55:53,952 INFO  [MyServerMonitor]

	Starting MyServerMonitor
12:55:53,952 INFO  [STDOUT]
	 1- Gotting InitialContext......
12:55:53,964 INFO  [STDOUT]
	 2- Got InitialContext: javax.naming.InitialContext@588a4b96
12:55:59,167 INFO  [STDOUT]

	===================MyServerMonitor.monitor()===================
BuildOS = Linux(i386,2.6.18-194.8.1.el5)
VersionName = JBoss AS
InShutdown = false
StartDate = Sun Oct 16 12:19:59 IST 2011
Started = true
BuildJVM = 17.0-b16(Sun Microsystems Inc.)
VersionNumber = 6.0.
	===============================================================

The MyServerMonitor.monitor() will be executed after every 5 Seconds as we have set this frequency as 5 seconds inside the jboss-service.xml file.

Step6). If you want to change this frequency to something else then you can login to jmx-console and then search for “service.server.monitor” in the left Panel then by clicking on it you will be able to see the frequency which you can change.

.
.
Thanks
Middleware Magic 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


  • 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