Chapter 1. JOnAS and JMX, registering and manipulating MBeans

Similar documents
BEAWebLogic Server. Monitoring and Managing with the Java EE Management APIs

Craig Walls Norman Richards. XDoclet IN ACTION MANNING

BEAWebLogic. Server. Monitoring and Managing with the J2EE Management APIs

Data Service Patterns Jeff Zhuk

BEAWebLogic. Server. Monitoring and Managing with the J2EE Management APIs

1 Introduction and Roadmap

Developing Java EE Management Applications for Oracle WebLogic Server c (12.1.3)

Oracle Fusion Middleware Developing Java EE Management Applications for Oracle WebLogic Server. 12c ( )

1 Introduction and Roadmap

JSP. Common patterns

Java code(assembler) ******************************************************************* package A1;

Creating Web Application with BEA WebLogic Workshop. Jeff (Yefim) Zhuk

Spring Soup with OC4J and MBeans

JBoss Remoting. Version alpha. November 15, 2004

BEAAquaLogic. Service Bus. JMX Monitoring API Programming Guide

Programming Assignment Comma Separated Values Reader Page 1

CS506 Web Design & Development Final Term Solved MCQs with Reference

Oracle Service Bus. JMX Monitoring API Programming Guide 10g Release 3 (10.3) October 2008

Highlights of Previous Lecture

Apache Felix Shell. Apache Felix Shell. Overview. How the Shell Service Works. package org.apache.felix.shell;

OpenClinica: Towards Database Abstraction, Part 1

Programming with the SCA BB Service Configuration API

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.

Highlights of Previous Lecture

COURSE DETAILS: CORE AND ADVANCE JAVA Core Java

Customizing the WebSphere Portal login and logout commands

WebServices - Axis 1.1. ## 1.2. #### 1.3. ######## API. 1. Axis ######### ##### 1.2 #######:

Page 1

Spring and Coherence Recipes

MODULE 6q - Exceptions

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

JBoss Remoting. Version beta. January 12, 2005

16-Dec-10. Consider the following method:

Techniques for Building J2EE Applications

Objects and Iterators

JAVA+ANDROID CURRICULUM 6 WEEKS. INTRODUCTION TO JAVA Understanding Requirement: Why Java Why Java is important to the Internet JAVA on LINUX Platform

HIBERNATE - INTERCEPTORS

Enhydra 6.2 Application Architecture. Tanja Jovanovic

Programming with the SCA BB Service Configuration API

Servlet for Json or CSV (or XML) A servlet serving either Json or CSV (or XML) based on GET parameter - This version uses org.json

Communicating with JMX agents. Using the RMI adapter from Sun Creating a Jini connector Creating a TCP adapter

Programming with the SCA BB Service Configuration API

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

Specialized - Mastering JEE 7 Web Application Development

Creating Manageable Systems With JMX, Spring, AOP, and Groovy

Ehcache Operations Guide. Version

Spring Certification Questions

API Developer Notes. A Galileo Web Services Java Connection Class Using Axis. 29 June Version 1.3

Using Properties for runtime ICAN 5.0.x JCD Configuration

BEAWebLogic. Server. Programming WebLogic Management Services with JMX

Artix ESB. Management Guide, Java Runtime. Version 5.5, December 2008

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

JAVA. Java Management Extensions JMX

WCS SOAP Based North Bound Application Program Interfaces (APIs) for Guest User Administration

Lightweight J2EE Framework

Assignments All about Servlets Servlet Exercise 1

Oracle 10g: Build J2EE Applications

Appendix: Assorted Sweets

Java Technologies Resources and JNDI

The Struts MVC Design. Sample Content

/ / JAVA TRAINING

ABOUT CORE JAVA COURSE SCOPE:

Administering the JBoss 5.x Application Server

/* Copyright 2012 Robert C. Ilardi

<Insert Picture Here> Hudson Web Architecture. Winston Prakash. Click to edit Master subtitle style

WA1278 Introduction to Java Using Eclipse

Oracle 1Z Java EE 6 Web Component Developer(R) Certified Expert.

/* JSPWiki - a JSP-based WikiWiki clone.

Managing Artix Solutions with JMX. Version 4.2, March 2007

MyBatis-Spring Reference Documentation

Diagnostic & Audit system for Java EE applications

Guide Organization JReport Monitor Server

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 8.

Server Extensions Developer Guide

The propeties file will contain a main.class property, maybe an optional main.method property, and a set of description properties.

Vendor: SUN. Exam Code: Exam Name: Sun Certified Web Component Developer for J2EE 5. Version: Demo

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling 2

AquaLogic BPM Process API

EJB 3.0 Programmer's Guide

From the book. Integration-Ready Architecture and Design. Cambridge University Press

Yes, it changes each time simulateonestep is invoked.

Tutorial: Developing a Simple Hello World Portlet

Full file at

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies

APIs - what are they, really? Web API, Programming libraries, third party APIs etc

Introduction to Cisco CDS Software APIs

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

Questions and Answers

Dynamic Datasource Routing

Servlets. How to use Apache FOP in a Servlet $Revision: $ Table of contents

MWTM NBAPI Integration for Java Developers

Exercise Session Week 6

Strut2 jasper report plugin - War deployment

Composite Pattern - Shapes Example - Java Sourcecode

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

15CS45 : OBJECT ORIENTED CONCEPTS

CS193j, Stanford Handout #26. Files and Streams

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

web.xml Deployment Descriptor Elements

Exceptions - Example. Exceptions - Example

Transcription:

Chapter 1. JOnAS and JMX, registering and manipulating MBeans Table of Contents 1.1. Introduction... 1 1.2. ServletContextListener... 1 1.3. Configuration... 4 1.4. Library Dependences... 4 1.5. HibernateService Extension... 5 By Jonny Way. 1.1. Introduction JMX (Java Management extensions) is an API for managing, among other things, J2EE applications. JOnAS (version 4 and above) integrates the MX4J open-source JMX server and registers a number of MBeans. The web-based JonasAdmin application acts as a JMX client, enabling viewing and manipulation of these MBeans. It maybe desirable for an application to expose its own MBeans via the JMX server to allow application management (using, for example, MC4J). JOnAS currently does not provide a prebuilt method for registering MBeans with its JMX server. The intent of this document is to illustrate one method of registering application-specific MBeans with the JOnAS JMX server based on the m-let service. 1.2. ServletContextListener The basic task of registering an MBean with the JOnAS JMX server is accomplished by the following implementation of the ServletContextListener [http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ ServletContextListener.html] interface. This implementation reads a number of MLet files, which specify the MBeans to be registered, and attempts to register those beans during the web application context initialization. import java.net.malformedurlexception; import java.net.url; import java.util.iterator; import java.util.arraylist; import java.util.list; import java.util.set; import java.util.stringtokenizer; import javax.management.instancealreadyexistsexception; import javax.management.instancenotfoundexception; import javax.management.reflectionexception; import javax.management.mbeanserver; import javax.management.mbeanexception; import javax.management.mbeanregistrationexception; import javax.management.mbeanserverfactory; import javax.management.malformedobjectnameexception; import javax.management.notcompliantmbeanexception; import javax.management.objectinstance; import javax.management.objectname; import javax.management.loading.mlet; import javax.management.loading.mletmbean; import javax.servlet.servletcontextevent; import javax.servlet.servletcontext; import javax.servlet.servletcontextlistener; import org.apache.log4j.logger; 1

/ ServletContextListener designed to register JMX MBeans into an existing JMX server when the application starts up. The MBeans to be loaded are specified in the MLet files whose names are given in the servlet context parameter with the name mletfiles, in a semi-colon delminated list (although this is not really needed as multiple mlets can be specifyed in one file, it might be useful). Note that the filename are relative to the WEB-INF directory of the servlet context being listened to. Note, that this listener should precede (in web.xml) any other that depend on the MBeans being registered. Note that the MBean registration is sensitive to classloader issues. For example, when registering the MBeans in the JMX server provided by the Jonas application server any libraries required by the MBeans need to be in the central lib directory (lib/ext). @author Jonny Wray / public class MBeanRegistrationListener implements ServletContextListener { private static final String MLET_DOMAIN = "MBeanRegistrationListener"; private static final String MLET_BEAN_NAME = MLET_DOMAIN+":Name=MLet"; private static final String MLETFILE_INITPARAM_NAME = "mletfiles"; private static final Logger log = Logger.getLogger(MBeanRegistrationListener.class); private MBeanServer lookforexistingserver(){ List mbeanservers = MBeanServerFactory.findMBeanServer(null); if(mbeanservers!= null && mbeanservers.size() > 0){ return (MBeanServer)mbeanServers.get(0); return null; private MBeanServer getmbeanserver(){ MBeanServer server = lookforexistingserver(); if(server == null){ server = MBeanServerFactory.createMBeanServer(MLET_DOMAIN); return server; public void contextdestroyed(servletcontextevent arg0) { log.info("destroy event"); // Anything that needs to be done here on deregistering of the // web application? private List getmleturls(string filenames){ List urls = new ArrayList(); StringTokenizer tok = new StringTokenizer(filenames, ";"); while(tok.hasmoretokens()){ String filename = tok.nexttoken(); URL configurl = Thread.currentThread().getContextClassLoader().getResource(filename); if(configurl == null){ log.error("cound not load MLet file resource from "+filename +" using current thread context classloader"); urls.add(configurl); return urls; private List getmleturls(servletcontext context, String filenames){ List urls = new ArrayList(); StringTokenizer tok = new StringTokenizer(filenames, ";"); while(tok.hasmoretokens()){ String filename = "/WEB-INF/"+tok.nextToken(); URL configurl = null; try { configurl = context.getresource(filename); 2

catch (MalformedURLException e) { log.error("url for "+filename+" is malformed", e); if(configurl == null){ log.error("cound not find MLet file resource from "+filename +" in servlet context"); urls.add(configurl); return urls; / Dynamically register the MBeans specified in the list of MLet files (relative to /WEB-INF/) specified in servlet context parameter mletfiles as a semi-colon deliminated list of file names. The algorithm looks for already running JMX servers and uses the first it comes across. If no servers are running, then it creates one. Note, the interface does not define any exceptions to be thrown. Currently, any exceptions thrown during registration are logged at error level and then ignored. This seems reasonable, as these may or may not be a fatal event. In this way the registration process reports its failure and the application context initialization continues. / public void contextinitialized(servletcontextevent arg0) { log.info("initializing event"); String filenames = arg0.getservletcontext().getinitparameter(mletfile_initparam_name); if(filenames!= null && filenames.length() > 0){ MBeanServer server = getmbeanserver(); if(server!= null){ try{ ObjectName name = new ObjectName(MLET_BEAN_NAME); if(!server.isregistered(name)){ log.info("creating new MLetMBean for dynamic registration"); MLetMBean mletservice = new MLet(); server.registermbean(mletservice, name); List urls = getmleturls(arg0.getservletcontext(), filenames); for(int i=0;i < urls.size();i++){ URL url = (URL)urls.get(i); try { log.info("registering MBeans from MLet file "+url); Set loadedmbeans = (Set)server.invoke(name, "getmbeansfromurl", new Object[]{url, new String[]{URL.class.getName()); processregisteredmbeans(loadedmbeans); from MLet file "+url, e); from MLet file "+url, e); from MLet file "+url, e); catch (InstanceNotFoundException e) { log.error("unable to register MBeans catch (MBeanException e) { log.error("unable to register MBeans catch (ReflectionException e) { log.error("unable to register MBeans catch(malformedobjectnameexception e){ catch(notcompliantmbeanexception e){ catch(mbeanregistrationexception e){ 3

catch(instancealreadyexistsexception e){ log.error("mbeanserver not found and could not be created. Not registering MBeans."); log.error("no mletfiles servlet context parameter found."); private void processregisteredmbeans(set loadedmbeans) { log.debug("loaded beans: "+loadedmbeans.size()); Iterator it = loadedmbeans.iterator(); while(it.hasnext()){ Object o = it.next(); if(o instanceof ObjectInstance){ ObjectInstance inst = (ObjectInstance)o; log.info("registered: "+inst.getobjectname()); else if(o instanceof Throwable){ Throwable err = (Throwable)o; log.error("error registering MBeans", err); 1.3. Configuration In order to use the above ServletContextListener, it must be configured in the web.xml of the web application that wants to register the MBeans. For example, the following lines added to the web.xml will result in the registeration of the MBeans specified in the application.mlet file under the WEB- INF directory. Multiple MLet files can be specified in a comma-separated list. <context-param> <param-name>mletfiles</param-name> <param-value>application.mlet</param-value> </context-param> <listener> <listener-class>net.fiveprime.jmx.mbeanregistrationlistener</listener-class> </listener> An example MLet file to load an extension (detailed below) of the HibernateService MBean is: <mlet code="configurablehibernateservice" name="hibernateservice:name=hibernateservice" archive="mbeans.jar"> <arg type="java.lang.string" value="hibernate.cfg.xml"> <arg type="java.lang.string" value="hibernate/hibernatesessionfactory"> <arg type="java.lang.string" value="defaultds"> </mlet> 1.4. Library Dependences Registration of MBeans results in their construction by the JMX server. As such, any classes the MBean is dependent on must be available to the JMX server, in lib/ext. 4

1.5. HibernateService Extension The Hibernate distribution provides an implementation of HibernateServiceMBean in the class HibernateService. In the MLet file above, an extension of this class is specified that allows the HibernateService to be configured from an external file, such as the standard hibernate.cfg.xml file. There are a number of situations where it is desirable to use the Hibernate mapped classes outside of Jonas running a JMX server. This allows the Hibernate mapping files and properties to be specified in one place and used in multiple situations. If this is not needed, then the HibernateService class can be used directly. import java.io.ioexception; import java.net.url; import java.util.arraylist; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; import net.sf.hibernate.hibernateexception; import net.sf.hibernate.jmx.hibernateservice; import org.apache.commons.digester.digester; import org.apache.commons.logging.log; import org.apache.commons.logging.logfactory; import org.xml.sax.saxexception; / Extension of the HibernateService class to add configuration ability from a Hibernate XML configuration file. @author Jonny Wray / public class ConfigurableHibernateService extends HibernateService { private static Log log = LogFactory.getLog(ConfigurableHibernateService.class); / Configure this HibernateService from an XML file @param filename The Hibernate XML configuration file, for example hibernate.cfg.xml @param jndiname The JNDI name that the session factory will be registered under @param datasourcename The name of the datasource used by the session factory @throws HibernateException If there's a problem reading the configuration file / public ConfigurableHibernateService(String filename, String jndiname, String datasourcename) throws HibernateException{ init(filename, jndiname, datasourcename); start(); private void init(string filename, String jndiname, String datasourcename) throws HibernateException { if(log.isdebugenabled()){ log.debug("configuring Hibernate JMX MBean with filename "+filename+ ", JNDI name "+jndiname+" and datasource "+datasourcename); try{ URL url = this.getclass().getclassloader().getresource(filename); Digester mappingdigester = configuremappingdigester(); List results = (List)mappingDigester.parse(url.openStream()); Iterator it = results.iterator(); while(it.hasnext()){ StringBuffer buffer = (StringBuffer)it.next(); addmapresource(buffer.tostring()); log.debug("adding mapping resource "+buffer.tostring()); Digester propertydigester = configurepropertydigester(); Map resultmap = (Map)propertyDigester.parse(url.openStream()); it = resultmap.keyset().iterator(); while(it.hasnext()){ 5

String key = (String)it.next(); String value = (String)resultMap.get(key); setproperty("hibernate."+key, value); log.debug("adding property ("+key+","+value+")"); setjndiname(jndiname); setdatasource(datasourcename); catch(ioexception e){ throw new HibernateException(e); catch(saxexception e){ throw new HibernateException(e); private Digester configuremappingdigester(){ Digester digester = new Digester(); digester.setclassloader(this.getclass().getclassloader()); digester.setvalidating(false); digester.addobjectcreate("hibernate-configuration/session-factory", ArrayList.class); digester.addobjectcreate("hibernate-configuration/session-factory/mapping", StringBuffer.class); digester.addcallmethod("hibernate-configuration/session-factory/mapping", "append", 1); digester.addcallparam("hibernate-configuration/session-factory/mapping", 0, "resource"); digester.addsetnext("hibernate-configuration/session-factory/mapping", "add"); return digester; private Digester configurepropertydigester(){ Digester digester = new Digester(); digester.setclassloader(this.getclass().getclassloader()); digester.setvalidating(false); digester.addobjectcreate("hibernate-configuration/session-factory", HashMap.class); "put", 2); "name"); 1); digester.addcallmethod("hibernate-configuration/session-factory/property", digester.addcallparam("hibernate-configuration/session-factory/property", 0, digester.addcallparam("hibernate-configuration/session-factory/property", return digester; 6