站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Adding Java Management Extensions (JMX) Instrumentation to a Java Application

Adding Java Management Extensions (JMX) Instrumentation to a Java Application

摘要: The NetBeans JMX Module integrates JMX technology right into your workflow in the NetBeans IDE. This module allows you to quickly develop management applications, add management to exisiting applications, develop manager applications, and monitor the state of the Virtual Machine. The module is available for NetBeans IDE version 4.0 and higher. You can install the module by choosing Tools > Update Center and downloading the module from the NetBeans Update Center.

Expected duration: 60 minutes

The NetBeans JMX Module integrates JMX technology right into your workflow in the NetBeans IDE. This module allows you to quickly develop management applications, add management to exisiting applications, develop manager applications, and monitor the state of the Virtual Machine. The module is available for NetBeans IDE version 4.0 and higher. You can install the module by choosing Tools > Update Center and downloading the module from the NetBeans Update Center.

This tutorial shows you how to add management to an existing application (the NetBeans sample Anagrams Game application). You will first create a non-manageable Anagram Java Project. You will then use JMX Wizards to generate 90% of the management. Then you will implement the management behavior specific to the application. You will finally use the Run/Debug project with JConsole to visualize the Anagram MBeans.

Prerequisites

This tutorial assumes you have some basic knowledge of, or programming experience with, the following technologies.

Tutorial exercises

Resources

Exercise 1: Creating the Sample Anagram Project

The goal of this exercise is to create a runnable Java Project. The Anagram game is a Swing Application. It displays a mixed-up word to the user and waits for the user to solve the anagram.

  1. Choose File > New Project (Ctrl-Shift-N).
  2. Select the Samples > General category.
  3. Select the Anagram Game project.
  4. Anagram 1

  5. Click Next. The Project Name and Location panel is displayed. Keep  the default values.
  6. Anagram 2

  7. Click Finish. A new anagrams project is created.

Exercise 2: Creating the Anagram JMX Standard MBean

The goal of this exercise is to create a JMX Standard MBean that allows you to monitor the time spent by the user to solve a new anagram. Each time an anagram is solved, a JMX notification is sent.

The MBean contains :

Steps to Follow

Be sure to have selected the anagrams project and to have set it as your main project.

  1. Choose File > New File (Ctrl-N).
  2. From the Management category, select JMX MBean and click Next. The MBean Name and Location panel is displayed.
  3. Create MBean 1

  4. Enter the following information and click Next:
    • Class Name: AnagramsStats
    • Location: Source Packages (default)
    • Package: com.toy.anagrams.mbeans

    Create MBean 2

  5. In the Type and Options page of the wizard, select Standard MBean as the MBean type. Add an MBean description (for example, Monitoring and Management of the Anagrams Game). Then click Next.
  6. Create MBean 3

  7. In the Attributes and Operations page, specify the MBean Attributes. Click the Add Attribute to add an Attribute row. Then specify the following information:
    • Attribute Name: LastThinkingTime
    • Type: int
    • Access: ReadOnly
    • Description: Time needed to solve

  8. Create MBean 4

  9. Click Next.
  10. Adding an operation is done the same way by clicking on the Add Operation button. Add an operation named resetAll that returns void, has no parameters, no exceptions, and which has a description of reset MBean state. Then click Next.
  11. Create MBean 8

  12. In the MBean Notifications, configure the way the current MBean will handle notifications:
    • Check the  Implement NotificationEmitter Interface checkbox.
    • Check the  Generate Delegation to Broadcaster checkbox. All methods  declared by the NotificationEmitter interface will be implemented by delegating to a notification broadcaster. A notification broadcaster simplifies the way the MBean will send notifications.
    • Check the Generate Private Seq Number and Accessor. Some code will be generated to handle the unique sequence number value that must be added to each notification that is sent.
  13. Add a notification by clicking on the Add Notification button. Change the Notification Class to be javax.management.AttributeChange using the drop-down list. Notice that the Notification Type is automatically set to ATTRIBUTE_CHANGE. This notification is sent each time an Anagram is solved. Set the description to Anagram is Solved.
  14. Create MBean 9


  15. The steps needed to create your MBean are now finished. Clicking Next allows you to generate a JUnit test, but we will not do this just yet. However, we will do it later. So, skip the last step and generate the MBean now by clicking on Finish.

The AnagramsStats MBean class and interface are generated in the anagrams project. Looking at the members view and at the generated code, you will notice that the getLastThinkingTime method is generated in the AnagramsStats class and in the AnagramsStatsMBean interface. A private field named lastThinkingTime of type int is also generated. It is used to store the attribute value.

    Create MBean 11

Summary

In this exercise, you have learned how to create an MBean using the MBean wizard.

Exercise 3: Updating the AnagramsStats MBean

Creating an MBean is generally an iterative task. You first generate an MBean with a set of Attributes and Operations, then you add/remove some. In this exercise we are going to add the attribute NumSolvedAnagrams to the MBean we generated previously.

Steps to Follow

  1. In the Projects tree, select the AnagramsStats node.
  2. Chosose Management > Add Attributes from the main menu. You can also access this contextual menu by right clicking on the selected node. Notice that you can also add some operations, generate a JUnit test, and much more.

    Update MBean

  3. The Add MBean Attributes dialog box is displayed. Notice that the LastThinkingTime attribute you defined above is displayed in the list of attributes. 
  4. Add the new attribute in exactly the same way as you did using the MBean Wizard:
    1. Click Add Attribute.
    2. Enter NumSolvedAnagrams as the attribute name.
    3. Set the type to int.
    4. Set the access to ReadOnly.
    5. Enter Number of solved anagrams as the attribute description.

    Update MBean 2

  5. Click OK. The method getNumSolvedAnagrams is added at the end of the AnagramsStats and AnagramsStatsMBean classes. A private field named numSolvedAnagrams of type int is added at the top of AnagramsStats class. It is used to store the attribute value.
  6. The MBean is now updated with the new attribute. We will now add some logic to the MBean.

Exercise 4: Implementing the AnagramsStats MBean

In this exercise, we will add some management logic to the AnagramsStats class.

Steps to Follow

  1. First, notice that the attributes NumSolvedAnagrams and LastThinkingTime are already implemented. They don't need any updates.
  2. The resetAll method needs to be implemented. The generated body is empty.  When resetAll is called, we simply set both counters to 0. Add the following code in the resetAll method body:
  3. lastThinkingTime = 0;
    numSolvedAnagrams = 0;
  4. Add some methods to the AnagramsStats class in order for the Anagrams UI class to notify the MBean that a new anagram has been proposed to the user, or that an anagram has been solved. Add some code to create and send a notification when an anagram is solved. Click here for the code to add to AnagramsStats class.
  5. Notice that a JMX notification of type ATTRIBUTE_CHANGE is sent each time an anagram is solved. The next figure shows the updated AnagramsStats class.
  6. Implement MBean

  7. You are done with the MBean implementation. Now we will generate a JUnit test then add some testing logic.

Summary

In this chapter you learned how to implement a Standard MBean. This is done in two phases. First you implement the management Attributes and Operations, then you add methods to allow MBean state updates.

Exercise 5: Generating a JUnit Test for the AnagramsStats MBean

In this exercise, you will learn how to generate a JUnit test for an MBean.  This generates a set of tests based on the MBean attributes and operations. With these special JUnit tests, you will not deal with the MBean deployment. You will only focus on testing the MBean Attributes and Operations.

Steps to Follow

  1. In the Projects tree, select the AnagramsStats node.
  2. Choose Management > Create JUnit Test form the main menu. You can also access this contextual menu by right clicking on the selected node. The Create JUnit Test dialog box is displayed.
  3. Create JUnit 1

    The created file com.toy.anagrams.mbeans.AnagramsStatsTest will be generated in the Test  packages. A list of MBean constructors is proposed.  The constructor you select will be used to instantiate the MBean before registering it in the MBean server. If  you need to provide some parameters to your MBean, you will have to update the generated createMBean method.

  4. Keep the default values and click OK. AnagramsStatsTest opens in the Source Editor.
  5. Create JUnit 2

Summary

In this exercise you learned how to create a JUnit test class for an MBean.

Exercise 6: Adding Logic to the JUnit AnagramsStatsTest Class

In this exercise, you will learn how to add logic to a JMX JUnit test and how to run the test. You will add a simple assertion in each test case.

Steps to Follow

  1. For each Attribute, a method named  testattribute_NameAttribute is generated. In this method, the attribute is obtained. We will then add some to test the returned value.
    • In the method testLastThinkingTimeAttribute, replace the call to fail("The test case is empty"); with assertTrue("The Last Thinking Time must be equals to 0", val == 0);
    • In the method  testNumSolvedAnagramsAttribute replace the call to fail("The test case is empty"); with assertTrue("The Num of Solved Anagrams must be equal to 0", val == 0);

    Update JUnit

  2. For each Operation, a method named  testoperation_NameOperation is generated. In this method, the operation is called. We will then add some logic to test that no exceptions were thrown.
    • In the method  testResetAllOperation replace the call to fail("The test case is empty"); with assertTrue("Method invoked successfully", true);

    Update JUnit 2

  3. Run the JMX JUnit test. Select the com.toy.anagrams.mbeans.AnagramsStatsTest class in Test packages. Right click, then select Run File in the popup menu. Test results are displayed in the JUnit Test Results window.
  4. Update JUnit 3

Summary

In this chapter, you learned how to update and run JMX JUnit tests. Now that we have an MBean, we need to create a container to deploy it. This is the role of the JMX Agent.

Exercise 7: Generating a JMX Agent

In this exercise, you will learn how to generate a JMX Agent. An agent is a simple runnable or non-runnable class that:

  1. Provides a method to create and register your MBeans.
  2. Provides access to the MBean server.
  3. Provides a singleton design pattern that allows you to easily access an initialized agent. An initialized agent is an agent that has all its MBean registered.
Note: A runnable Agent (one that contains a main method) is generated when you want to create a management application. Non-runnable agents are used when you want to add management to an application. This tutorial shows the latter of these agents. We will add management to the Anagrams game, which already has a main runnable class.

You will also learn how to add an MBean to an Agent and how to make the MBean accessible from the agent.

Steps to Follow

  1. Choose File > New File (Ctrl-N).
  2. Select the JMX Agent template from the Management category and click Next.
  3. Create Agent

  4. In the Name and Location page, type JMXAgent as the Class Name. Set com.toy.anagrams.agent for the Package. Unselect the Create Main Method checkbox. (In this tutorial we are instrumenting an application that already has a main.) Then click Finish.
  5. Create Agent 2

  6. The JMXAgent class is generated in your project. The JMXAgent class is opened in the editor pane. Note the init method and its commented sample code that shows you how to manually register an MBean.
  7. Create Agent 3

Exercise 8: Adding the AnagramsStats MBean to the Agent

In this exercise, you will learn how to add an MBean to a JMX Agent. Adding an MBean to an Agent involves:

This module provides you with a utility that handles these tasks.

Info

Best practices when naming your MBeans :

Applying best practices will make the way you name your MBeans more formalized. The ObjectName we are creating is :type=AnagramsStats.


Steps to Follow:

  1. In the Projects tree, select the JMXAgent node.
  2. Choose Management > Instantiate and Register MBean from the main menu. The Instantiate and Register MBean dialog box is displayed.
  3. Add MBean

  4. Click the Browse button to select your MBean. The current project tree is displayed. 
  5. Select Source Packages > com.toy.anagrams.mbeans > AnagramsStats.
  6. Add MBean 2

  7. Click OK. The dialog box is updated with the MBean you selected. The MBean ObjectName is computed automatically. The discovered MBean constructors are displayed.
  8. Add MBean 3

  9. Keep the default values and click OK. The JMXAgent init method is updated with the MBean registration code.
  10. Add MBean 4

  11. In the context of this tutorial, an extra step is required. We want the application to have access to the class implementing the management interface (AnagramsStats). This is not a general rule but it can be useful when your application needs to push data to an MBean. The startThinking and stopThinking methods are used by the application to notify the MBean that some events have occured. In turn, the MBean updates its state. In order to make AnagramsStats accessible from the Anagrams UI class, we need to modify the init method and add an MBean accessor to the agent. The following image shows the parts of the JMXAgent class that must be updated (click on the image for a larger view).
  12. Add MBean 5

     

    You have finished your agent instrumentation. We are now going to connect the anagrams game and the JMX management layer together.

Summary

In this chapter you learned how to instrument a JMX Agent. Mainly. You added MBean creation and registration code to the init method. You also provided accessors to provide local access to the MBean.

Exercise 9: Connecting Management and the Application Together

In this exercise, you will learn how to access the MBean from the application and how to implement the management logic. This is very simple and can be achieved with just a few lines of code.

Steps to Follow:

  1. Double-click the Anagrams UI main class in the com.toy.anagrams.ui package. The class opens in the IDE's Design view.
  2. Click Source at the top of the Source Editor to edit the class in the Source view.
  3. Add a call to the initManagement method in the Anagrams class constructor.
  4. Implement an initManagement private mehod.
    1. Access the JMXAgent singleton instance. This will have the side effect of registering the AnagramsStats MBean.
    2. Access the AnagramsStats MBean and call startThinking() on it. When the anagrams game is first displayed, an anagram is displayed. So we need to compute the time at the very beginning of the application's execution.

    Instrument Anagram 1 - click for fullsize


  5. We now need to add code to track the user's anagram solving experience. Add code in 2 places:
    1. Each time a new anagram is proposed to the user, we must compute the start time. This is done in the nextTrialActionPerformed method.
    2. Each time an anagram is guessed correctly, we need to notify the MBean that the thinking time is over. This is done in the guessedWordActionPerformed method.

    Instrument Anagram 2 - click for fullsize


    You are have finished linking the JMX layer to the application layer. We are now going to execute the application and play a little bit with the Anagrams game.

Exercise 10: Running the Application with JConsole

In this exercise, you will learn how to compile, run your project, and connect JConsole to visualize the JVM state, as well as the application MBeans.

Steps to Follow

  1. A single step performs all these tasks. Click the Run with JConsole icon in the toolbar.
  2. A dialog box warns you that the build.xml files will be updated. Just click OK.
  3. Run 1 - click for fullsize

    You can follow the execution in the output console.

    Run 2 - click for fullsize

  4. The Anagram game is displayed. Don't click on guess right now. First set up JConsole to display information.
  5. Run 3 - click for fullsize

  6. JConsole is displayed. Select the MBeans tab.
  7. Run 4 - click for fullsize

  8. Select the AnagramsStats MBean, then select the Notifications tab.
  9. Run 5 - click for fullsize

  10. Subscribe to notifications. JConsole will receive a new notification each time an anagram is solved.
  11. Run 6 - click for fullsize

  12. Go back to the Attributes tab and double-click the LastThinkingTime value to plot the thinking time.
  13. In the Anagrams window, solve the first anagram (It is easy, but I'll give you the first answer: abstraction).
  14. Notice that the attributes are updated and that JConsole received a notification. You can select the Notifications tab to visualize the notification details.
  15. Run 8 - click for fullsize

  16. Don't forget that we added a management operation resetAll. You can access MBean Operations by selecting the Operations tab. You then have to click the resetAll button. Notice that the MBean attribute values changed to 0.

Yes! You are done! You did a really good job.

I hope that this tutorial helped you understand how to add management to your application. You should be able to apply what you learned to your development.


↑返回目录
前一篇: Adding Functionality to Buttons: A Beginners Guide
后一篇: Asynchronous JAX-WS Web Service Client End-to-End Scenario