Chapter 1. Getting Started

This chapter will give you step-by-step instructions to writing a managed bean (MBean). It will also show you how to deploy the MBean to an agent. If you have no previous knowledge of the JMX specification or MBeans, you should take the time to read through the chapter. However, if you are already familiar with the MBean concept and the JMX API, feel free to use this chapter as a review and just quickly glance through it.

In the following examples, both the Sun JMX Reference Implementation and the IBM Tivoli JMX Implementation are used. Two different implementations are used to illustrate the portability of the MBeans across the implementations but also to point out the differences of the two implementations when using features the JMX specification does not define. Such features include the JMX connectors and protocol adaptors.

After you have finished reading this chapter, you will have the basic knowledge required for JMX development using Standard MBeans. You will also know how to register an MBean to an agent and will have the basic knowledge of how to work with at least two different JMX implementations.

MBean Component Types

MBeans are components that implement a management interface, either statically, in which case the management interface is a Java interface, or dynamically, in which case the management interface is defined through a set of metadata classes.

The JMX specification defines four different MBean component types, three of which are mandatory in the current 1.0 version of the specification. The different component types are as follows:

  • Standard MBean

  • Dynamic MBean

  • Model MBean

  • Open MBean

The Standard, Dynamic, and Model MBeans are mandatory and must be implemented by all compliant JMX implementation. The Open MBeans were not finished for the 1.0 version of the specification and are not required. However, at the time of this writing, a maintenance release of the specification is in the works and that might change the status of the Open MBeans from optional to mandatory as well.

Standard MBeans are created by declaring a Java interface with the management information that the MBean must implement. The other three component types describe their management interfaces through a set of metadata classes. Model MBeans extend the Dynamic MBeans by allowing additional descriptors to be added to the management interface. Open MBeans restrict the object types used in the management interface to a predefined set of classes representing the basic types.

The MBeans are registered to an agent that is able to manipulate the registered management components. The agent acts as a registry for MBeans offering a means to query and modify the managed components via their management interface. The relationship between the agent and the MBean components is shown in Figure 1.1.

Overview of the agent and MBean components.

Figure 1.1. Overview of the agent and MBean components.

Another important aspect to notice in Figure 1.1 is that management clients are always decoupled from the actual managed resources represented by the MBeans. All communications between the clients and the MBeans are carried through the agent level, and no direct references to the MBean components are ever exposed outside the agent. This is a significant feature of the JMX-based management architecture, and you will study it more in the Chapter 2, “Architecture,” when we go through all the details of the architecture.

Writing Your First MBean

You will start by writing a Standard MBean using the traditional “Hello, World” example. For now, you need not to worry about all the details of the specification or the rules and requirements for MBeans. Concentrate on this specific example. We will cover the specification in the next chapters, but for now it is important for you to familiarize yourself with the basics of JMX development.

You will build a managed bean where we expose a single attribute that is both readable and writable by the management application. We will also expose one management operation of our MBean. What you will notice during this example is that writing a Standard MBean implementation is no different from implementing a normal Java interface. In fact, writing the MBean implementation is very close to writing a regular JavaBean component with setter and getter methods for manipulating the attributes.

The MBean interface design follows similar naming conventions to those described in the JavaBeans component specification. The difference between your MBean and JavaBean component is that you'll explicitly define and implement an interface that describes the management attributes and operations of the MBean. This results in a Standard MBean, which is often the easiest and most straightforward way to enable Java classes to management.

The following example consists of three different parts.

  • Management interface declaration

  • Implementation of the resource you want to manage

  • Application code to instantiate the agent and register the managed bean

After you are done with the example, you will have an MBean deployed to the agent and can manipulate its attributes and operations through a Web management interface.

Management Interface Declaration

The first part of the example follows the traditional “Hello, World” approach to learning new technologies. First, you will define the management interface and call it HelloMBean. The interface declares three methods: two for accessing a management attribute Name and one management operation print(). The code for the management interface is shown in Listing 1.1.

Example 1.1. HelloMBean.java

package book.jmx.examples;

public interface HelloMBean {

       // management attributes
       public String getName();
       public void setName(String name);

       // management operations
       public void print();

}

As you can see in the HelloMBean.java, declaring a management interface does not differ from declaring an ordinary Java interface. However, you should pay attention to some of the details in the declaration. First, notice how the interface has been named.

public interface HelloMBean {

The suffix MBean is significant. The agent, to which the MBean is registered (see Figure 1.1), uses the introspection features of the Java programming language to look for an interface named with the MBean suffix. The interface name identifies the class implementing it as a Standard MBean. When developing standard MBeans, you must follow this naming convention to name all of your management interfaces. In the example, we have named the interface as HelloMBean, which the JMX agent will automatically recognize as a Standard MBean interface. The agent will then use introspection to find the MBean attributes and operations from the interface. The actual implementation class, or managed resource as it is called in JMX terminology, will be called Hello. Notice the relationship between the classname and the management interface name.

In the management interface, we also declare a read-write attribute Name. To declare a management attribute, and to let the agent know it is a read-write attribute, we declared two accessor methods—getName() and setName().

// management attributes
public String getName();
public void setName(String name);

The attribute's name is recognized by the agent that looks for methods matching the MBean attribute naming convention in the interface. In this example, the MBean attribute Name is readable because you have defined a method getName(). The attribute is also writable because you have defined a setter method setName(). You could also declare just one accessor method for the Name attribute, resulting in either a read-only or write-only management attribute.

Last, you declare one management operation in the interface. It is a simple operation that doesn't require parameters or return any values when invoked.

// management operations
public void print();

You are free to name your management operations as you want. In fact, all the methods declared in the MBean interface not matching the naming convention of a management attribute, such as getName() and setName(), are interpreted by the JMX agent as management operations. Therefore, in this case, the method print() is interpreted as a management operation instead of an attribute.

That is all there was to writing the management interface. If you were to enable a management of existing classes via the means of Standard MBeans, you would write the interface exposing the attributes and operations and name the interface after the MBean naming convention. If you are already following the common Java naming practices, there is little you need to change in your existing code. In the optimal case, all you need to do is declare your class to implement the MBean interface that tells the JMX agent which methods and operations you are exposing to the management from your class.

Implementing the MBean

Because you are not exposing a management interface to an existing class but creating a new managed resource, you will also write the class implementing the Standard MBean interface. The Hello class in Listing 1.2 is a public, non-abstract class that implements the HelloMBean interface you saw in HelloMBean.java file in Listing 1.1.

Example 1.2. Hello.java

package book.jmx.examples;

public class Hello implements HelloMBean {

       private String name = "";

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

       public void print() {
              System.out.println("Hello, " + name + "!!" );
      }

}

The Hello class stores the attribute state in the name field whenever the setName() method is invoked and returns the contents of name when getName() is called. We don't explicitly declare a constructor but rely on the Java default constructor to provide a public constructor required by compliant MBeans.

Again, it's worth it to notice the relationship between the classname Hello and the corresponding name of the management interface HelloMBean that it implements. This naming convention is required for all Standard MBeans.

The Hello class is very trivial Java class by any measure, but it will serve as an example when deploying the MBean and testing it. You will be able to use a Web-based interface to set the attribute value and invoke the print operation. Next, you will look at how to instantiate the agent, register the managed bean, and set up a Web interface to manage it.

Deploying the HelloMBean

You have now declared the management interface and written the resource class you want to manage. The third part of the example involves instantiating the agent and registering the managed bean to it. You will set up the agent, called MBean server, and use its programming interface to register your management component. The MBean server implementation is provided with the JMX implementation. At the time of this writing, there are at least three JMX implementations publicly available. Sun Microsystems provides a reference implementation of the JMX specification at http://java.sun.com/products/JavaManagement/index.html. In addition, the IBM Tivoli team offers a JMX implementation at http://www.alphaworks.ibm.com. The third implementation is provided by AdventNet at http://www.adventnet.com.

Regardless of which JMX implementation you decide to use, the agent level implements the same MBeanServer interface. All access to the managed beans is invoked through this interface, so the example in this chapter is portable across both the Sun and IBM Tivoli JMX implementations. It should also work on any other compatible JMX implementation. You should note that the MBeans and their interfaces are never directly exposed to the management applications. From the MBeans' point of view, all invocations arrive from the agent to which it is registered. From the client application's point of view, all invocations are made to the MBeanServer interface. Remember that there is never a direct object reference between the client and the managed resource.

Listing 1.3 shows the details of creating the agent and registering the MBean. The JMX agent implements the MBeanServer interface. You will use this interface to add new MBeans, register them to the JMX infrastructure, and query the existing MBeans in the agent. You will get an in-depth look at the classes and interfaces of the agent in Chapter 6, “MBean Server.” For now, all you need to do is create an agent instance and register the example MBean.

To create an instance of the agent, use the MBeanServerFactory class available in the javax.management package. This factory class contains a static method createMBeanServer() that will return a reference to an object implementing the agent. In the case of a Sun Microsystems reference implementation, you get back a reference to Sun's implementation of the agent; in the case of the Tivoli JMX implementation, you are returned a reference to Tivoli's JMX agent.

After you receive the agent reference, you can use it to register the Hello MBean implementation. The MBeanServer interface contains a registerMBean() method that you will use to register the Hello MBean component to the agent. The code to accomplish this is shown in Listing 1.3.

Example 1.3. Agent.java

package book.jmx.examples;

import javax.management.*;


public class Agent {

    // the main method of the class
    public static void main(String[] args) {

        try {
            // create the agent reference
            MBeanServer server =
                MBeanServerFactory.createMBeanServer();

            // create reference to the MBean
            ObjectName name =
                new ObjectName("example:name=hello");

            // register Hello MBean
            server.registerMBean(new Hello(), name);
      }
      catch (MBeanRegistrationException e) {
        e.printStackTrace();
      }
      catch (NotCompliantMBeanException e) {
        e.printStackTrace();
      }
      catch (MalformedObjectNameException e) {
        e.printStackTrace();
      }
      catch (InstanceAlreadyExistsException e) {
        e.printStackTrace();
      }
    }
}

Listing 1.3 creates the agent and registers the MBean but does little else. To manipulate the MBean, you can either write more Java code to programmatically invoke methods of the MBean interface, or you can use existing management tools to change the attributes and invoke management operations on the Hello MBean.

For this example, you will use the tools provided by the Sun and Tivoli JMX implementations to view and manipulate the registered MBean. The MBean server itself is a local object to the Java Virtual Machine (JVM) and does not offer means to remotely connect to it. For all calls coming outside the JVM, remotely or from another process in the local machine, the JMX connectors or protocol adaptors are used. These components are often implemented as MBeans themselves, and registered as part of the agent, allowing a wide variety of connectivity to the MBean server. We will cover the architectural view of connectors and protocol adaptors in Chapter 2 and then implement some of them in the second part of the book.

You will use an HTTP protocol adaptor that both implementations provide to remotely manage the Hello MBean. Something you need to be aware of at this point is that the JMX specification, in its 1.0 version, does not define any standard protocol adaptors or connectors. This means that every time we discuss or use either an adaptor or a connector in this book, we have moved outside the scope of the current specification and are using JMX implementation specific features. Work is currently under way in the Java Community Process to define specifications for standard connectors, and it is likely that some of those will end up in the future versions of the JMX specification.

Note

JMX protocol adaptors and connectors are not part of the current 1.0 version of the JMX specification.

Deployment with Sun JMX Reference Implementation

Sun provides an HTTP protocol adaptor with its JMX Reference Implementation in a class com.sun.jdmk.comm.HtmlAdaptorServer. As you can see from the package name, it is not part of the JMX API but a class from Sun's Java Dynamic Management Kit (JDMK) that is a commercial product offered by Sun Microsystems.

You can download the reference implementation that includes the specification classes and some additional classes, such as the HTTP adaptor, from Sun's Web site at http://java.sun.com/products/JavaManagement/index.html. Download the reference implementation binary code release and save and extract the zip onto your hard drive. The zip file contains the usual JavaDoc API documentation, library jar files, and some sample code. For our example, we are interested in two jar files in the jmx-1_0_1-ri_bin/jmx/lib directoryjmxri.jar and jmxtools.jar.

The jmxri.jar file contains the JMX API classes required to compile the Java sources. It also contains the implementation classes for the JMX agent. The jmxtools.jar file contains the classes required by the Sun HTTP adaptor.

Extract the required files and compile the three classes you wrote (Hello.java, HelloMBean.java, and Agent.java). Copy the three Java files and the Sun reference implementation zip package to your working directory and execute the next set of commands.

The first command will unzip the archive using the Java archive tool to your working directory. The second command will compile the three files we wrote for this example, using the libraries in the archive that should be found under directory jmx-1_0_1-ri_bin/jmx/lib after the archive is extracted. The third command will run the agent application.

For more detailed instructions on how to set up the Java development environment, the JMX implementations, and other libraries needed in examples later, please refer to Appendix A, “Environment Setup.”

C: Examples> jar –xf jmx-1_0-ri-bin.zip

C: Examples> javac –d . –classpath .;jmx-1_0_1-ri_bin/jmx/lib/jmxri
Deployment with Sun JMX Reference Implementation.jar;jmx-1_0_1-ri_bin/jmx/lib/jmxtools.jar Hello.java HelloMBean.java Agent.java

C: Examples> java –classpath .;jmx-1_0_1-ri_bin/jmx/lib/jmxri.jar; jmx-1_0_1-ri_bin/jmx
Deployment with Sun JMX Reference Implementation/lib/jmxtools.jar book.jmx.examples.Agent

Unix and Linux users should notice that you will need to use a colon : separator in your classpath instead of the semicolon.

If everything worked correctly, you should have three compiled classes. If you encountered an error, please see the detailed setup instructions in Appendix A.

When you started the agent, you probably noticed that it did not do anything visible. It started and then immediately stopped. We will change that behavior next by adding a few lines to the agent that will create and register the Sun HTTP protocol adaptor implementation. The protocol adaptor itself is an MBean, so we will use the registerMBean() method call to register it to the MBean server. Again, remember that the adaptor is not part of the current 1.0 version of the JMX specification.

The code changes to the Agent.java file to register the HTTP adaptor are highlighted in Listing 1.4.

Example 1.4. Agent.java

...

    try {
      // create the agent reference
      MBeanServer server =
      MBeanServerFactory.createMBeanServer();

      // create reference to the MBean
      ObjectName name =
      new ObjectName("example:name=hello");

      // register Hello MBean
      server.registerMBean(new Hello(), name);

      // create the adaptor instance
      com.sun.jdmk.comm.HtmlAdaptorServer adaptor =
      new com.sun.jdmk.comm.HtmlAdaptorServer();

      // register the adaptor MBean to the agent
      server.registerMBean(adaptor,
      new ObjectName("adaptor:protocol=HTTP"));

      // start the adaptor
      adaptor.start();
    }
    catch (MBeanRegistrationException e) {
      e.printStackTrace();
    }

...

Compile the Agent.java file again and run it. Notice that the execution did not end immediately this time. This time, an HTTP adaptor instance was created, registered and started. The agent now has a thread waiting for incoming HTTP requests from the network. By default, the thread is listening for HTTP requests on port 8082. You can now open your Web browser and point it to the address http://localhost:8082. It should open the page shown in Figure 1.2.

The HTML page generated by the Sun HTTP Adaptor.

Figure 1.2. The HTML page generated by the Sun HTTP Adaptor.

Figure 1.2 shows the HTML page generated by the protocol adaptor. It lists the registered MBeans, including the HTTP adaptor MBean as well. The last entry on the page in Figure 1.2 shows your Hello MBean under the example domain with the name property set as hello. Click the link under Example and you will be able to manipulate the MBean.

On the next HTML page shown in Figure 1.3, you will see a list of the MBean's attributes. The attribute Name that we added as a read-write attribute to the Hello MBean is shown here with its type, access (RW), and value. The default value for Name is an empty string. You can change it by typing a new value in the text field, for example World, as can be seen in Figure 1.3. Click the Apply button and the Web browser will refresh the page displaying the new value in the text field. You have just changed the value of a managed attribute in the MBean.

HTML View of the HelloMBean.

Figure 1.3. HTML View of the HelloMBean.

Also one management operation is exposed in the MBean, the print() method. At the end of the HTML page in Figure 1.3, you will see the HTTP adaptor listing the MBean's management operations. The adaptor has included a Print button for the operation in the Web page. Click the button and the page will change to say Print Successful. Now go look at the console from which you started the agent and you should see it has printed the string

Hello, World!!

This is the result of executing the management operation on the MBean through a Web browser from a local machine. It could have just as easily been remotely over the network. You can try the remote access with a Web browser from another machine if you have a local network set up.

You have now created an MBean, registered it to the agent, manipulated its attributes, and invoked a management operation remotely via a Web page. As you hopefully noticed, creating the MBean was quite effortless and, in return, you have gained the ability to remotely manage a software component over the network via a Web browser.

Deployment with Tivoli JMX Implementation

The Tivoli JMX implementation works similarly to the Sun reference implementation. Remember that all of the MBean code you wrote is portable between the implementations. What you need to change is the Agent.java file to use a different HTTP adaptor class.

First download the Tivoli JMX implementation from IBM alphaWorks Web site at http://www.alphaworks.ibm.com. At the time of this writing, there are two distributions available, one for Windows NT and another for Sun Solaris. The packages contain some platform-specific code, but you are not going to need that so either one of the downloads should work. The following installation instructions are for the Windows NT package.

Extract the files from the zip. The jmxc.jar and jmxx.jar files contain the JMX API classes and the Tivoli JMX implementation classes. Inside the jmxext.jar, you can find the HTTP adaptor implementation in addition to other connector classes, for example the RMI connector. In the example, you will use only the HTTP adaptor.

To compile the agent using the Tivoli JMX implementation, execute the next sequence of commands. If you modified the Agent.java source to include references to Sun HTTP adaptor class earlier, remember to remove them first. Again, the first command will unzip the archive using the Java Archive tool. The second command will recompile all the Java files, this time with the Tivoli JMX libraries that can be found in the tmx4j/base/lib and tmx4j/ext/lib directories after extracting the archive.

C: Examples> jar –xf tmx4j_NT_1_2.zip

C: Examples> javac -d . –classpath .;tmx4j/base/lib/jmxc.jar;tmx4j/base/lib/ jmxx
Deployment with Tivoli JMX Implementation.jar;tmx4j/ext/lib/jmxext.jar Hello.java HelloMBean.java Agent.java

C: Examples> java -classpath .;tmx4j/base/lib/jmxc.jar;tmx4j/base/lib/jmxx.jar; tmx4j
Deployment with Tivoli JMX Implementation/base/lib/log.jar;tmx4j/ext/lib/jmxext.jar book.jmx.examples.Agent

You should be able to run the agent and it will execute once and then exit. Unix and Linux users need to remember to replace the semicolon in classpaths with a colon.

Now let's add the Tivoli HTTP adaptor to the agent code. The changes to add the adaptor to the original Agent.java file are in bold in Listing 1.5.

Example 1.5. Agent.java

...

    try {
        MBeanServer server =
            MBeanServerFactory.createMBeanServer();

        ObjectName name = new
            ObjectName("example:name=hello");
        server.registerMBean(new Hello(), name);

        // create the adaptor instance
        com.tivoli.jmx.http_pa.Listener adaptor =
            new com.tivoli.jmx.http_pa.Listener();
        // register the adaptor MBean to the agent
        server.registerMBean(adaptor,
            new ObjectName("adaptor:protocol=HTTP"));

        // start the adaptor
        adaptor.startListener();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    catch (MBeanRegistrationException e) {
        e.printStackTrace();
    }

...

Recompile and run the agent. This time the execution will not end immediately, and you can point your Web browser to the http://localhost:6969 page. Notice that the default port number is different from the Sun reference implementation. When you start the agent, you should see the following message on the console.

The HTTP Adaptor started on port number 6969

When you open the browser, you will see a Find an MBean link on the front page. Click the link and it will open another page that will allow you to query the registered beans in the agent. In the query field, type the name of the MBean, example:name=hello. Be aware that the query string is case sensitive (see Figure 1.4).

The HTML View generated by the Tivoli HTTP Adaptor.

Figure 1.4. The HTML View generated by the Tivoli HTTP Adaptor.

After you submit the query, you will see a list of MBeans matching the object name filter. In this case, the result set has only one MBean, the Hello example. Click the link and a new page with the MBean's details will open. Notice that the agent has recognized the MBean's type as standard (see Figure 1.5), it lists the attributes we have exposed in the MBean and it displays the print() operation that we declared in the MBean interface as a management operation. Click the Name attribute and change its value to World. Then click the print() operation and press the Invoke Operation button on the page that the browser opened. You should see the hello message in the agent console window.

HTML View of the Hello MBean.

Figure 1.5. HTML View of the Hello MBean.

Hello, World!!

That is all there is to it to make the Hello MBean work with another JMX implementation. The only change we needed to make was to register a different HTTP protocol adaptor in the agent. The actual MBean code was portable and worked unchanged with both implementations using their specific Web-based management applications.

Summary

In this chapter, you saw how to define an interface for a Standard MBean, had a brief look at the JMX API, and created an instance of a management agent. You then proceeded to deploy the MBean on both Sun Microsystems' JMX reference implementation and Tivoli's JMX implementation. In both of these cases, you also saw how to start the implementation-specific HTTP adaptors and how they can be used to query and manipulate the MBean attributes and remotely invoke the management methods.

By now, you should have some basic idea how MBeans can be built and how generic management tools, such as the HTTP adaptor, can be used to manage resources without having to build custom management solutions and user interfaces for them. This gives you a solid base to proceed to the following chapters, which will take you into the details of the JMX specification.

For those curious to take a peek at the specification before continuing, you can download it from Sun's Web site at http://java.sun.com/products/JavaManagement/index.html. Also, there is a mailing list available for discussion of the specification that you can read at http://archives.java.sun.com/jmx-forum.html.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.17.18