JVM

Curl Based Management & Monitoring in JBossAS7 with HTTP-JSON APIs

Trust me None other Application Server provides this kind of amazing feature, except JBossAS7. JBoss AS7 is one of the bestest application available in the Middleware World, As it provides much more facilities to the Administrators in order to manage/configure and monitor various resources. As we are already familier with a utility called as “$JBOSS_HOME/bin/jboss-cli.sh” is one of the most powerful and easiest utility which can be used to manage and monitor JBossAS7.

In this demonstration we will see that JBoss AS7 provides another best feature, which allows us to easily access & monitor & management the JBoss AS7 using OS level utilities like “curl”. Yes, JBoss AS7 provides HTTP-JSON based APIs which can be used to achieve the same. So lets see some of it’s features…

So lets start JBossAS7 like following:

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

NOTE: In all the following operations we will assume that you have created a ManagementRealm User with username “admin” and password as “admin123″ (you can create any user name/password based on your requirement), Then change the username & password in the mentioned demo URLs like “http://admin:admin123@localhost:9990/management/”

NOTE: Curl is a free utility for non-interactive download of files from the Web.

So Open a Terminal (command prompt) and start testing the following Curl command on your JBossAS7

Checking Server State

curl --digest -L -D - http://admin:admin123@localhost:9990/management --header "Content-Type: application/json" -d '{"operation":"read-attribute","name":"server-state","json.pretty":1}'

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="07d65fc8e028df9ed577145c8e973c64"
Date: Sun, 23 Sep 2012 15:18:59 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 15:18:59 GMT

{
    "outcome" : "success",
    "result" : "running"
}

Editing “max-pool-size” attribute of ExampleDS DataSource

curl --digest -L -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"write-attribute","address":[{"subsystem":"datasources"},{"data-source":"ExampleDS"}],"name":"max-pool-size","value":10}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="57d99ff484d2b950ecfde2bcd8c7b55c"
Date: Sun, 23 Sep 2012 15:27:32 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 15:27:32 GMT

Editing “min-pool-size” attribute of ExampleDS DataSource

curl --digest -L -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"write-attribute","address":[{"subsystem":"datasources"},{"data-source":"ExampleDS"}],"name":"min-pool-size","value":5}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="662bd288e4949b0093b8d1c5db704a6a"
Date: Sun, 23 Sep 2012 15:33:37 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 15:33:37 GMT

Changing console-handler “CONSOLE” logging level to “WARN”


curl --digest -L -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"write-attribute","address":[{"subsystem":"logging"},{"console-handler":"CONSOLE"}],"name":"level","value":"WARN", "json.pretty":1}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="8ad3a0fd0b5f393c8cf9ac757d8395d3"
Date: Sun, 23 Sep 2012 20:00:07 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 20:00:07 GMT

{"outcome" : "success"}

Testing ExampleDS datasource connections

curl --digest -L -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"test-connection-in-pool","address":[{"subsystem":"datasources"},{"data-source":"ExampleDS"}]}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="2feecad0028c0122ed04c2bf344fdde3"
Date: Sun, 23 Sep 2012 16:47:29 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 16:47:30 GMT

{"outcome" : "success", "result" : [true]}

Getting JVM Memory & Runtime Details

curl --digest -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"read-resource", "include-runtime":"true", "address":[{"core-service":"platform-mbean"},{"type":"memory"}], "json.pretty":1}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="86d37639bcc651b1cea47a91bef0be14"
Date: Sun, 23 Sep 2012 19:44:19 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 19:44:19 GMT

{
    "outcome" : "success",
    "result" : {
        "heap-memory-usage" : {
            "init" : 1366294528,
            "used" : 161655864,
            "committed" : 1324351488,
            "max" : 1324351488
        },
        "non-heap-memory-usage" : {
            "init" : 24313856,
            "used" : 61050320,
            "committed" : 61210624,
            "max" : 318767104
        },
        "object-name" : "java.lang:type=Memory",
        "object-pending-finalization-count" : 0,
        "verbose" : false
    }
}

Getting JBoss Runtime Details

curl --digest -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"read-resource", "include-rutime":"true", "address":[{"core-service":"platform-mbean"},{"type":"runtime"}], "json.pretty":1}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="b2d05e49490da200cdd74bd7f848998e"
Date: Sun, 23 Sep 2012 19:45:22 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 19:45:22 GMT

{
    "outcome" : "success",
    "result" : {
        "name" : "24028@localhost.localdomain",
        "vm-name" : "Java HotSpot(TM) 64-Bit Server VM",
        "vm-vendor" : "Oracle Corporation",
        "vm-version" : "23.1-b03",
        "spec-name" : "Java Virtual Machine Specification",
        "spec-vendor" : "Oracle Corporation",
        "spec-version" : "1.7",
        "management-spec-version" : "1.2",
        "class-path" : "/home/userone/jboss-as-7.1.2/jboss-modules.jar",
        "library-path" : "/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib",
        "boot-class-path-supported" : true,
        "boot-class-path" : "/home/userone/jdk1.7.0_05/jre/lib/resources.jar:/home/userone/jdk1.7.0_05/jre/lib/rt.jar:/home/userone/jdk1.7.0_05/jre/lib/sunrsasign.jar:/home/userone/jdk1.7.0_05/jre/lib/jsse.jar:/home/userone/jdk1.7.0_05/jre/lib/jce.jar:/home/userone/jdk1.7.0_05/jre/lib/charsets.jar:/home/userone/jdk1.7.0_05/jre/lib/jfr.jar:/home/userone/jdk1.7.0_05/jre/classes",
        "input-arguments" : [
            "-D[Standalone]",
            "-XX:+UseCompressedOops",
            "-Xms1303m",
            "-Xmx1303m",
            "-XX:MaxPermSize=256m",
            "-Djava.net.preferIPv4Stack=true",
            "-Dorg.jboss.resolver.warning=true",
            "-Dsun.rmi.dgc.client.gcInterval=3600000",
            "-Dsun.rmi.dgc.server.gcInterval=3600000",
            "-Djboss.modules.system.pkgs=org.jboss.byteman",
            "-Djava.awt.headless=true",
            "-Djboss.server.default.config=standalone.xml",
            "-Dorg.jboss.boot.log.file=/home/userone/jboss-as-7.1.2/standalone/log/boot.log",
            "-Dlogging.configuration=file:/home/userone/jboss-as-7.1.2/standalone/configuration/logging.properties"
        ],
        "start-time" : 1348315286154,
        "system-properties" : {
            "[Standalone]" : "",
            "awt.toolkit" : "sun.awt.X11.XToolkit",
            "catalina.home" : "/home/userone/jboss-as-7.1.2/standalone/tmp",
            "ddddd" : "eeeee",
            "file.encoding" : "UTF-8",
            "file.encoding.pkg" : "sun.io",
            "file.separator" : "/",
            "java.awt.graphicsenv" : "sun.awt.X11GraphicsEnvironment",
            "java.awt.headless" : "true",
            "java.awt.printerjob" : "sun.print.PSPrinterJob",
            "java.class.path" : "/home/userone/jboss-as-7.1.2/jboss-modules.jar",
            "java.class.version" : "51.0",
            "java.endorsed.dirs" : "/home/userone/jdk1.7.0_05/jre/lib/endorsed",
            "java.ext.dirs" : "/home/userone/jdk1.7.0_05/jre/lib/ext:/usr/java/packages/lib/ext",
            "java.home" : "/home/userone/jdk1.7.0_05/jre",
            "java.io.tmpdir" : "/tmp",
            "java.library.path" : "/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib",
            "java.naming.factory.url.pkgs" : "org.jboss.as.naming.interfaces:org.jboss.ejb.client.naming",
            "java.net.preferIPv4Stack" : "true",
            "java.protocol.handler.pkgs" : "org.jboss.net.protocol|org.jboss.vfs.protocol",
            "java.runtime.name" : "Java(TM) SE Runtime Environment",
            "java.runtime.version" : "1.7.0_05-b05",
            "java.specification.name" : "Java Platform API Specification",
            "java.specification.vendor" : "Oracle Corporation",
            "java.specification.version" : "1.7",
            "java.util.logging.manager" : "org.jboss.logmanager.LogManager",
            "java.vendor" : "Oracle Corporation",
            "java.vendor.url" : "http://java.oracle.com/",
            "java.vendor.url.bug" : "http://bugreport.sun.com/bugreport/",
            "java.version" : "1.7.0_05",
            "java.vm.info" : "mixed mode",
            "java.vm.name" : "Java HotSpot(TM) 64-Bit Server VM",
            "java.vm.specification.name" : "Java Virtual Machine Specification",
            "java.vm.specification.vendor" : "Oracle Corporation",
            "java.vm.specification.version" : "1.7",
            "java.vm.vendor" : "Oracle Corporation",
            "java.vm.version" : "23.1-b03",
            "javax.management.builder.initial" : "org.jboss.as.jmx.PluggableMBeanServerBuilder",
            "javax.xml.datatype.DatatypeFactory" : "__redirected.__DatatypeFactory",
            "javax.xml.parsers.DocumentBuilderFactory" : "__redirected.__DocumentBuilderFactory",
            "javax.xml.parsers.SAXParserFactory" : "__redirected.__SAXParserFactory",
            "javax.xml.stream.XMLEventFactory" : "__redirected.__XMLEventFactory",
            "javax.xml.stream.XMLInputFactory" : "__redirected.__XMLInputFactory",
            "javax.xml.stream.XMLOutputFactory" : "__redirected.__XMLOutputFactory",
            "javax.xml.transform.TransformerFactory" : "__redirected.__TransformerFactory",
            "javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema" : "__redirected.__SchemaFactory",
            "javax.xml.xpath.XPathFactory:http://java.sun.com/jaxp/xpath/dom" : "__redirected.__XPathFactory",
            "jboss.home.dir" : "/home/userone/jboss-as-7.1.2",
            "jboss.host.name" : "localhost",
            "jboss.modules.dir" : "/home/userone/jboss-as-7.1.2/modules",
            "jboss.modules.system.pkgs" : "org.jboss.byteman",
            "jboss.node.name" : "localhost",
            "jboss.qualified.host.name" : "localhost.localdomain",
            "jboss.server.base.dir" : "/home/userone/jboss-as-7.1.2/standalone",
            "jboss.server.config.dir" : "/home/userone/jboss-as-7.1.2/standalone/configuration",
            "jboss.server.data.dir" : "/home/userone/jboss-as-7.1.2/standalone/data",
            "jboss.server.default.config" : "standalone.xml",
            "jboss.server.deploy.dir" : "/home/userone/jboss-as-7.1.2/standalone/data/content",
            "jboss.server.log.dir" : "/home/userone/jboss-as-7.1.2/standalone/log",
            "jboss.server.name" : "localhost",
            "jboss.server.temp.dir" : "/home/userone/jboss-as-7.1.2/standalone/tmp",
            "line.separator" : "\n",
            "logging.configuration" : "file:/home/userone/jboss-as-7.1.2/standalone/configuration/logging.properties",
            "module.path" : "/home/userone/jboss-as-7.1.2/modules",
            "org.apache.coyote.http11.Http11Protocol.COMPRESSION" : "on",
            "org.apache.coyote.http11.Http11Protocol.COMPRESSION_MIME_TYPES" : "text/javascript,text/css,text/html",
            "org.apache.coyote.http11.Http11Protocol.COMPRESSION_MIN_SIZE" : "5",
            "org.jboss.as.logging.per-deployment" : "false",
            "org.jboss.boot.log.file" : "/home/userone/jboss-as-7.1.2/standalone/log/boot.log",
            "org.jboss.com.sun.CORBA.ORBUseDynamicStub" : "true",
            "org.jboss.resolver.warning" : "true",
            "org.jboss.security.context.ThreadLocal" : "true",
            "org.omg.CORBA.ORBClass" : "org.jacorb.orb.ORB",
            "org.omg.CORBA.ORBSingletonClass" : "org.jacorb.orb.ORBSingleton",
            "org.osgi.vendor.framework" : "org.jboss.osgi.framework",
            "org.xml.sax.driver" : "__redirected.__XMLReaderFactory",
            "os.arch" : "amd64",
            "os.name" : "Linux",
            "os.version" : "3.4.9-2.fc16.x86_64",
            "path.separator" : ":",
            "sun.arch.data.model" : "64",
            "sun.boot.class.path" : "/home/userone/jdk1.7.0_05/jre/lib/resources.jar:/home/userone/jdk1.7.0_05/jre/lib/rt.jar:/home/userone/jdk1.7.0_05/jre/lib/sunrsasign.jar:/home/userone/jdk1.7.0_05/jre/lib/jsse.jar:/home/userone/jdk1.7.0_05/jre/lib/jce.jar:/home/userone/jdk1.7.0_05/jre/lib/charsets.jar:/home/userone/jdk1.7.0_05/jre/lib/jfr.jar:/home/userone/jdk1.7.0_05/jre/classes",
            "sun.boot.library.path" : "/home/userone/jdk1.7.0_05/jre/lib/amd64",
            "sun.cpu.endian" : "little",
            "sun.cpu.isalist" : "",
            "sun.desktop" : "gnome",
            "sun.io.unicode.encoding" : "UnicodeLittle",
            "sun.java.command" : "/home/userone/jboss-as-7.1.2/jboss-modules.jar -mp /home/userone/jboss-as-7.1.2/modules -jaxpmodule javax.xml.jaxp-provider org.jboss.as.standalone -Djboss.home.dir=/home/userone/jboss-as-7.1.2 -Djboss.server.base.dir=/home/userone/jboss-as-7.1.2/standalone -c standalone-full.xml -Dorg.jboss.as.logging.per-deployment=false",
            "sun.java.launcher" : "SUN_STANDARD",
            "sun.jnu.encoding" : "UTF-8",
            "sun.management.compiler" : "HotSpot 64-Bit Tiered Compilers",
            "sun.os.patch.level" : "unknown",
            "sun.rmi.dgc.client.gcInterval" : "3600000",
            "sun.rmi.dgc.server.gcInterval" : "3600000",
            "user.country" : "US",
            "user.dir" : "/home/userone/jboss-as-7.1.2/bin",
            "user.home" : "/home/jsenshar",
            "user.language" : "en",
            "user.name" : "jsenshar",
            "user.timezone" : "Asia/Calcutta"
        },
        "uptime" : 114236761,
        "object-name" : "java.lang:type=Runtime"
    }
}

Getting Server Environment Details

curl --digest -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"read-resource", "include-runtime":"true", "address":[{"core-service":"server-environment"}], "json.pretty":1}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="39385b83b7b9b2abbd722a3bdb4d7173"
Date: Sun, 23 Sep 2012 19:47:56 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 19:47:56 GMT

{
    "outcome" : "success",
    "result" : {
        "base-dir" : "/home/userone/jboss-as-7.1.2/standalone",
        "config-dir" : "/home/userone/jboss-as-7.1.2/standalone/configuration",
        "config-file" : "/home/userone/jboss-as-7.1.2/standalone/configuration/standalone-full.xml",
        "content-dir" : "/home/userone/jboss-as-7.1.2/standalone/data/content",
        "data-dir" : "/home/userone/jboss-as-7.1.2/standalone/data",
        "deploy-dir" : "/home/userone/jboss-as-7.1.2/standalone/data/content",
        "ext-dirs" : [
            "/home/userone/jdk1.7.0_05/jre/lib/ext",
            "/usr/java/packages/lib/ext"
        ],
        "home-dir" : "/home/userone/jboss-as-7.1.2",
        "host-name" : "localhost",
        "initial-running-mode" : "NORMAL",
        "launch-type" : "STANDALONE",
        "log-dir" : "/home/userone/jboss-as-7.1.2/standalone/log",
        "modules-dir" : "/home/userone/jboss-as-7.1.2/modules",
        "node-name" : "localhost",
        "qualified-host-name" : "localhost.localdomain",
        "server-name" : "localhost",
        "temp-dir" : "/home/userone/jboss-as-7.1.2/standalone/tmp"
    }
}

Getting Runtime Statistics of Http Connector of web subsystem

curl --digest -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"read-resource", "include-runtime":"true", "address":[{"subsystem":"web"},{"connector":"http"}], "json.pretty":1}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="37b5ee0cb0dde6f3963e7660a4439862"
Date: Sun, 23 Sep 2012 19:51:16 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 19:51:16 GMT

{
    "outcome" : "success",
    "result" : {
        "bytesReceived" : "0",
        "bytesSent" : "0",
        "enable-lookups" : false,
        "enabled" : true,
        "errorCount" : "0",
        "executor" : null,
        "max-connections" : 20,
        "max-post-size" : 2097152,
        "max-save-post-size" : 4096,
        "maxTime" : "0",
        "name" : "http",
        "processingTime" : "0",
        "protocol" : "HTTP/1.1",
        "proxy-name" : null,
        "proxy-port" : null,
        "redirect-port" : 8433,
        "requestCount" : "0",
        "scheme" : "http",
        "secure" : false,
        "socket-binding" : "http",
        "ssl" : null,
        "virtual-server" : null
    }
}

Shutting down JBoss Standalone Server

curl --digest -D - http://admin:admin123@localhost:9990/management/ -d '{"operation":"shutdown" , "json.pretty":1}' -HContent-Type:application/json

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="dd74ab565fbf5345ebb015cbd337ffea"
Date: Sun, 23 Sep 2012 20:08:02 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 20:08:02 GMT

{"outcome" : "success"}

Getting Application “TestLogging.ear” Details

curl --digest -D - http://admin:admin123@localhost:9990/management --header "Content-Type: application/json" -d '{"operation":"read-resource", "address":["deployment","TestLogging.ear"], "json.pretty":1}' 

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="486aa728c5bd526ab1bf1b96941252e2"
Date: Sat, 22 Sep 2012 11:07:38 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sat, 22 Sep 2012 11:07:38 GMT

{
    "outcome" : "success",
    "result" : {
        "content" : [{
            "path" : "deployments/TestLogging.ear",
            "relative-to" : "jboss.server.base.dir",
            "archive" : false
        }],
        "enabled" : true,
        "name" : "TestLogging.ear",
        "persistent" : false,
        "runtime-name" : "TestLogging.ear",
        "subsystem" : null,
        "subdeployment" : {
            "Log4jDemoOne.war" : null,
            "Log4jDemoTwo.war" : null
        }
    }
}

Getting Runtime Statistics of “Test_EAR.ear” application (session/request monitoring)

curl --digest -D - http://admin:admin123@localhost:9990/management --header "Content-Type: application/json" -d '{"operation":"read-resource","recursive":"true", "include-runtime":"true", "address":["deployment","Test_EAR.ear"], "json.pretty":1}'

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="80f9f113cda3ea0430c0a1474ac9b736"
Date: Sun, 23 Sep 2012 20:20:29 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sun, 23 Sep 2012 20:20:29 GMT

{
    "outcome" : "success",
    "result" : {
        "content" : [{"hash" : {
            "BYTES_VALUE" : "mSLytFVBop/W+VqanbNUztt7DRY="
        }}],
        "enabled" : true,
        "name" : "Test_EAR.ear",
        "persistent" : true,
        "runtime-name" : "test_trn.ear",
        "status" : "no metrics available",
        "subsystem" : null,
        "subdeployment" : {"Test_WAR.war" : {"subsystem" : {"web" : {
            "active-sessions" : 1,
            "context-root" : "/Test_WAR",
            "duplicated-session-ids" : 0,
            "expired-sessions" : 0,
            "max-active-sessions" : 1,
            "rejected-sessions" : 0,
            "servlet" : null,
            "session-avg-alive-time" : 0,
            "session-max-alive-time" : 0,
            "sessions-created" : 1,
            "virtual-host" : "default-host"
        }}}}
    }
}

Getting JNDI view details (list Jndi) / (jndi-view)

curl --digest -D - http://admin:admin123@localhost:9990/management --header "Content-Type: application/json" -d '{"operation":"jndi-view", "address":["subsystem","naming"], "json.pretty":1}'

HTTP/1.1 401 Unauthorized
Content-length: 0
Www-authenticate: Digest realm="ManagementRealm",nonce="e92a46c2e34810ed0084542cc59ca38f"
Date: Sat, 22 Sep 2012 11:13:29 GMT

HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: application/json
Date: Sat, 22 Sep 2012 11:13:29 GMT

{
    "outcome" : "success",
    "result" : {
        "java: contexts" : {
            "java:" : {
                "ConnectionFactory" : {
                    "class-name" : "org.hornetq.jms.client.HornetQJMSConnectionFactory",
                    "value" : "HornetQConnectionFactory [serverLocator=ServerLocatorImpl [initialConnectors=[org-hornetq-core-remoting-impl-invm-InVMConnectorFactory?server-id=0], discoveryGroupConfiguration=null], clientID=null, dupsOKBatchSize=1048576, transactionBatchSize=1048576, readOnly=false]"
                },
                "JmsXA" : {
                    "class-name" : "org.hornetq.ra.HornetQRAConnectionFactoryImpl",
                    "value" : "org.hornetq.ra.HornetQRAConnectionFactoryImpl@59ffb3fa"
                },
                "TransactionManager" : {
                    "class-name" : "com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate",
                    "value" : "com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate@13190ef8"
                },
                "ejb" : {
                    "class-name" : "javax.naming.Context",
                    "children" : {"mgmt" : {
                        "class-name" : "javax.naming.Context",
                        "children" : null
                    }}
                },
                "jboss" : {
                    "class-name" : "javax.naming.Context",
                    "value" : "org.jboss.as.naming.WritableServiceBasedNamingStore@6ab0fa3b"
                }
            },
            "java:jboss" : {
                "ORB" : {
                    "class-name" : "org.jacorb.orb.ORB",
                    "value" : "org.jacorb.orb.ORB@274fb2cf"
                },
                "TransactionManager" : {
                    "class-name" : "com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate",
                    "value" : "com.arjuna.ats.jbossatx.jta.TransactionManagerDelegate@13190ef8"
                },
                "TransactionSynchronizationRegistry" : {
                    "class-name" : "com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple",
                    "value" : "com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionSynchronizationRegistryImple@61644832"
                },
                "UserTransaction" : {
                    "class-name" : "org.jboss.tm.usertx.client.ServerVMClientUserTransaction",
                    "value" : "org.jboss.tm.usertx.client.ServerVMClientUserTransaction@5e6d855c"
                },
                "corbanaming" : {
                    "class-name" : "org.omg.CosNaming._NamingContextExtStub",
                    "value" : "IOR:000000000000002B49444C3A6F6D672E6F72672F436F734E616D696E672F4E616D696E67436F6E746578744578743A312E3000000000000100000000000000B0000102000000000A3132372E302E302E31000DC8000000114A426F73732F4E616D696E672F726F6F74000000000000040000000000000008000000004A4143000000000100000020000000000501000100000001000100010001010900000002050100010001010000000014000000080000001A00000DC90000002100000030000000000000000100000000000000220000000000000000000000000000000000000000000000000000000000000000"
                },
                "irpoa" : {
                    "class-name" : "org.jacorb.poa.POA",
                    "value" : "org.jacorb.poa.POA@7ebffc91"
                },
                "jaas" : {
                    "class-name" : "$Proxy13",
                    "children" : {
                        "jboss-ejb-policy" : {
                            "class-name" : "org.jboss.as.security.plugins.SecurityDomainContext",
                            "value" : "org.jboss.security.authentication.JBossCachedAuthenticationManager@7c1e7bee"
                        },
                        "other" : {
                            "class-name" : "org.jboss.as.security.plugins.SecurityDomainContext",
                            "value" : "org.jboss.security.authentication.JBossCachedAuthenticationManager@355a85eb"
                        },
                        "jboss-web-policy" : {
                            "class-name" : "org.jboss.as.security.plugins.SecurityDomainContext",
                            "value" : "org.jboss.security.authentication.JBossCachedAuthenticationManager@4a0e22aa"
                        }
                    }
                },
                "poa" : {
                    "class-name" : "org.jacorb.poa.POA",
                    "value" : "org.jacorb.poa.POA@6605ece1"
                },
                "mail" : {
                    "class-name" : "javax.naming.Context",
                    "children" : {"Default" : {
                        "class-name" : "javax.mail.Session",
                        "value" : "javax.mail.Session@3e475bbb"
                    }}
                },
                "datasources" : {
                    "class-name" : "javax.naming.Context",
                    "children" : {"ExampleDS" : {
                        "class-name" : "org.jboss.jca.adapters.jdbc.WrapperDataSource",
                        "value" : "org.jboss.jca.adapters.jdbc.WrapperDataSource@9b534aa"
                    }}
                },
                "exported" : {
                    "class-name" : "javax.naming.Context",
                    "value" : "org.jboss.as.naming.WritableServiceBasedNamingStore@579489e0"
                }
            },
            "java:global" : null
        },
        "applications" : {"TestLogging.ear" : {
            "java:app" : {
                "AppName" : {
                    "class-name" : "java.lang.String",
                    "value" : "TestLogging"
                },
                "env" : {
                    "class-name" : "org.jboss.as.naming.NamingContext",
                    "children" : null
                }
            },
            "modules" : null
        }}
    }
}

Dumping JBoss Services which are active

curl --digest -D - http://admin:admin123@localhost:9990/management --header "Content-Type: application/json" -d '{"operation":"dump-services", "address":["core-service","service-container"], "json.pretty":1}'

.
.
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 :)


Generating HeapDump while running JBoss as a Windows Service

Hi,

This article is very important in case of JBoss running as a Windows Service, Because if we run any Server JBoss or any other application server as a Windows Service then NONE of the JVM utilities like “jmap”, “jconsole” , “jps” or “VisualVM”… etc will work. So it becomes very difficult to collect the Thread Dump or Heap Dump of the Running Service.

We wrote an article based on JMX to collect the JVM’s memory related statistics using JMX code “Monitoring Heap & NonHeap Memory of JBoss using MBean code. Here we are extending the same program to make the JMX program to even collect the HeapDump whenever we want.

To connect to the actual JConsole remotely also we need to provide the following JAVA_OPTS inside our “$JBOSS_HOME/bin/run.bat” (run.conf.bat) file the connection url format should be:

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

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

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

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

Step2). Now from any other box or from the same Box you can run the Following JMX code to generate the HeapDump of the JVM process:
“GenerateHeapDump.java”

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

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

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

	private static void getHeapDump(String fileName) throws Exception
	{
		ObjectName memoryMXBean=new ObjectName("com.sun.management:type=HotSpotDiagnostic");
		Object[] params = new Object[] { "C:/WindowsService_Script/"+fileName, Boolean.TRUE };
		String[] signature = new String[] { String.class.getName(), boolean.class.getName() };
		Object result = connection.invoke(memoryMXBean, "dumpHeap" , params, signature);
		System.out.println("nt Heap Dump Generated to " +fileName);
	}

	public static void main(String[] args) throws Exception
	{
	String hostname = args[0];
	String port = args[1];
	Connection(hostname, port);
	System.out.println("nt----------Generating Heap Dump---------");
	getHeapDump("HeapDump.hprof");
	connector.close();
	}
}

Step3). Run your JBoss Windows Service and then compile and run your Program to generate the HeapDump

C:WindowsService_Script>set PATH=c:jdk160_05bin;%PATH%;
C:WindowsService_Script>javac GenerateHeapDump.java

C:WindowsService_Script>java GenerateHeapDump 10.10.10.10 4545
GOT THE MBeanServerConnection---SUCCESSFULLY

        ----------Generating Heap Dump---------
         Heap Dump Generated to HeapDump.hpro

NOTE: you will find the generated HeapDump in the "C:/WindowsService_Script/" directory in the Box where the JBoss is running as a Service which is defined in line -39 in above code.

.
.
Thanks
Middleware Magic Team


Monitoring Heap & NonHeap Memory of JBoss using MBean code

Hi,

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

javac  HeapAndNonHeapMonitoring.java
java  HeapAndNonHeapMonitoring  10.10.10.10  4545

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

OUTPUT:

java HeapAndNonHeapMonitoring localhost 4545
GOT THE MBeanServerConnection---SUCCESSFULLY

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

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

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

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

.
.
Thanks
Middleware Magic Team


  • Receive FREE Updates


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



  • Magic Archives

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