Вы находитесь на странице: 1из 59

Chapter 24 Java Management Extensions (JMX)

Outline 24.1 Introduction 24.2 Installation 24.3 Case Study 24.3.1 Instrument Resources 24.3.2 Implement the JMX Management Agent 24.3.3 Broadcasting and Receiving Notifications 24.3.4 Management Application 24.3.5 Compiling and Running the example 24.4 Internet and World Wide Web Resources

2001 Prentice Hall, Inc. All rights reserved.

24.1 Introduction Network management problems Current network management solutions


agents

Recent technological advances JMX


Three-level management architecture
Instrumentation level Agent level Management level

2001 Prentice Hall, Inc. All rights reserved.

24.1 Introduction JMX provides


Platform-independence Protocol-independence Reusable Intelligent agent Scalability

2001 Prentice Hall, Inc. All rights reserved.

24.1 Introduction

Manager Level

Management Application

Agent Level

Java Dynamic Management Agent

Instrumentation Level

Managed Resource

Managed Resource

Managed Resource

2001 Prentice Hall, Inc. All rights reserved.

24.2 Installation Implementation of JMX


Java Dynamic Management Kit (JDMK)

Download JDMK
www.sun.com/software/java-dynamic/try.html

Set CLASSPATH
jdmkrt.jar and jdmktk.jar

2001 Prentice Hall, Inc. All rights reserved.

24.3 Case Study Management solution


Resource Agent Application

MBean MBean server

2001 Prentice Hall, Inc. All rights reserved.

24.3 Case Study

Management Application

RmiConnectorClient: 5555

RmiConnectorServer: 5555 MBeanServer

Printer MBean

PrinterEventBroadcaster MBean

PrinterSimulator

2001 Prentice Hall, Inc. All rights reserved.

24.3.1 Instrument Resources Instrument a resource


Standard MBean
MBean interface MBean class

MBean interface design pattern


Naming Expose attributes of a management interface Methods Operations Serializable

2001 Prentice Hall, Inc. All rights reserved.

24.3.1 Instrument Resources MBean class design pattern


Implement MBean interface Public and concrete Public constructor

2001 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

// Fig. 22.3: PrinterMBean.java // This class specifies the interface that will be implemented // by Printer, which will function as an MBean. // deitel package package com.deitel.advjhtp1.jmx.PrinterSimulator; public interface PrinterMBean { // is it printing? public Boolean isPrinting(); // is it online? public Boolean isOnline(); // is paper jammed? public Boolean isPaperJam(); // returns paper amount in tray public Integer getPaperTray(); // returns ink level in toner cartridge public Integer getToner();

Outline
Interface PrinterMBean 1. Declarations

Interface name with MBean suffix

Management interface

Return value is serializable

// returns ID of print job that is currently printing public String getCurrentPrintJob(); // returns array of all queued up print jobs public String [] getPendingPrintJobs(); // sets availability status of printer public void setOnline ( Boolean online );

is, get, set methods

2001 Prentice Hall, Inc.


All rights reserved.

Outline
34 35 36 37 38 39 40 41 42 // fills up paper tray again with paper public void replenishPaperTray(); // cancel pending print jobs public void cancelPendingPrintJobs(); // start printing process public void startPrinting(); }

operations

1 2 3 4 5 6 7 8 9 10 11 12 13 14

// Fig. 22.4: PrinterEventListener.java // The listener interface for printer events. // Deitel package package com.deitel.advjhtp1.jmx.Printer; public interface PrinterEventListener { public void outOfPaper(); public void lowToner(); public void paperJam(); }

Interface PrinterEventListener

2001 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

// // // //

Fig. 22.5: Printer.java This class provides implementation for PrinterMBean interface and registers a managing MBean for the Printer device, which is simulated by PrinterSimulator.java.

Outline
Class Printer 1. Declarations 2. Constructor 2.1 connect to printer device

// deitel package package com.deitel.advjhtp1.jmx.PrinterSimulator; // Java core package import java.lang.Thread; import java.util.ArrayList; // JMX core packages import javax.management.*; // Deitel packages import com.deitel.advjhtp1.jmx.Printer.*; public class Printer implements PrinterMBean, PrinterEventListener { private private private private private private PrinterSimulator printerSimulator; static final int PAPER_STACK_SIZE = 50; ObjectInstance eventBroadcasterInstance; ObjectName eventBroadcasterName; ObjectName printerName; MBeanServer mBeanServer;

MBean class implements responding MBean interface

public Printer() Public constructor { // connect to the printer device printerSimulator = new PrinterSimulator( this ) ; Thread myThread = new Thread( printerSimulator ) ; myThread.start();

Connect to printer device

2001 Prentice Hall, Inc.


All rights reserved.

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

// find all MBean servers in current JVM ArrayList arrayList = MBeanServerFactory.findMBeanServer( null );

Find MBean servers

Outline
2.2 find MBean servers 2.3 specify MBean server requirement 2.4 identify MBean server

// retrieve the MBeanServer reference if ( arrayList.size() == 0) System.out.println( "Cannot find a MBeanServer!" ); else { // get the MBeanServer that has the // PrinterEventBroadcaster MBean registered with it for ( int i = 0; i < arrayList.size(); i++ ) { MBeanServer foundMBeanServer = ( MBeanServer )arrayList.get( i ); // obtain the object name for the // PrinterEventBroadcaster MBean try { String name = foundMBeanServer.getDefaultDomain() + ":type=" + "PrinterEventBroadcaster"; eventBroadcasterName = new ObjectName( name ); } // handle exception when creating ObjectName catch ( MalformedObjectNameException exception ) { exception.printStackTrace(); }

Specify MBean server requirement

// check whether the PrinterEventBroadcaster MBean is // registered with this MBeanServer if ( foundMBeanServer.isRegistered( Identify MBean server eventBroadcasterName ) ) { mBeanServer = foundMBeanServer; 2001 Prentice Hall, Inc. break; } All rights reserved.

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

} // end for loop } // end if-else to get the MBeanServer reference } // end PrinterSimulator constructor // will stop the printer thread from executing // once execution should stop. public void stop() { printerSimulator.stop(); } // Is it printing? public Boolean isPrinting() { return new Boolean( printerSimulator.isPrinting() ); } // is online? public Boolean isOnline() { return printerSimulator.isOnline(); } // is paper jammed? public Boolean isPaperJam() { return printerSimulator.isPaperJam(); } // is paper tray empty? public Integer getPaperTray() { return printerSimulator.getPaperTray(); }

Outline
3. Implement management solution

2001 Prentice Hall, Inc.


All rights reserved.

109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

Outline
// is toner low? public Integer getToner() { return printerSimulator.getToner(); } // returns ID of print job that is currently printing public String getCurrentPrintJob() { return printerSimulator.getCurrentPrintJob(); } // returns array of all queued up print jobs public String[] getPendingPrintJobs() { return printerSimulator.getPendingPrintJobs(); } // sets status availability of printer public void setOnline( Boolean online ) { if ( online.booleanValue() == true ) printerSimulator.setOnline(); else printerSimulator.setOffline(); } // fills up the paper tray again with paper. public void replenishPaperTray() { printerSimulator.replenishPaperTray ( Printer.PAPER_STACK_SIZE ); } 3. Implement management solution

2001 Prentice Hall, Inc.


All rights reserved.

Outline
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 // cancel pending print jobs public void cancelPendingPrintJobs() { printerSimulator.cancelPendingPrintJobs(); } // start the printing process public void startPrinting() { printerSimulator.startPrintingProcess(); } // send out of paper event to JMX layer public void fireOutOfPaperEvent() { // construct parameters and signatures Object[] parameter = new Object[ 1 ]; parameter[ 0 ] = new Notification( "PrinterEvent.OUT_OF_PAPER", this, 0L ); String[] signature = new String[ 1 ]; signature[ 0 ] = "javax.management.Notification"; // invoke notification try { mBeanServer.invoke( eventBroadcasterName, "sendNotification", parameter, signature ); } // handle exception when invoking method catch ( ReflectionException exception ) { exception.printStackTrace(); } 4. Send out-of-paper notification 4.1 specify notification 4.2 send notification

Specify notification

Send notification

2001 Prentice Hall, Inc.


All rights reserved.

Outline
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 // handle exception when communicating with MBean catch ( MBeanException exception ) { exception.printStackTrace(); } // handle exception if MBean not found catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } } // end method outOfPaperEvent // send low toner event to JMX layer public void fireLowTonerEvent() { // construct parameters and signatures Object[] parameter = new Object[ 1 ]; parameter[ 0 ] = new Notification( "PrinterEvent.LOW_TONER", this, 0L ); String[] signature = new String[ 1 ]; signature[ 0 ] = "javax.management.Notification"; // invoke notification try { mBeanServer.invoke( eventBroadcasterName, "sendNotification", parameter, signature ); } // handle exception when invoking method catch ( ReflectionException exception ) { exception.printStackTrace(); } 5. Send low-toner notification 5.1 specify notification 5.2 send notification

Specify notification

Send notification

2001 Prentice Hall, Inc.


All rights reserved.

Outline
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 // handle exception communicating with MBean catch ( MBeanException exception ) { exception.printStackTrace(); } // handle exception if MBean not found catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } } // end method lowTonerEvent // send paper jam event to JMX layer public void firePaperJamEvent() { // construct parameters and signatures Object[] parameter = new Object[ 1 ]; parameter[ 0 ] = new Notification( "PrinterEvent.PAPER_JAM", this, 0L ); String[] signature = new String[ 1 ]; signature[ 0 ] = "javax.management.Notification"; // invoke notification try { mBeanServer.invoke( eventBroadcasterName, "sendNotification", parameter, signature ); } // handle exception when invoking method catch( ReflectionException exception ) { exception.printStackTrace(); } 6. Send paper-jam notification 6.1 specify notification

Specify notification

Send notification

2001 Prentice Hall, Inc.


All rights reserved.

Outline
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 // handle exception communicating with MBean catch( MBeanException exception ) { exception.printStackTrace(); } // handle exception if MBean not found catch( InstanceNotFoundException exception ) { exception.printStackTrace(); } } // end method paperJamEvent // interface implementation public void outOfPaper() { // delegate call fireOutOfPaperEvent(); } // interface implementation public void lowToner() { // delegate call fireLowTonerEvent(); } // interface implementation public void paperJam() { // delegate call firePaperJamEvent(); } } 6.2 send notification

Interface implementation

2001 Prentice Hall, Inc.


All rights reserved.

Outline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 // Fig. 22.6: PrinterSimulator.java // This class simulates a printer device on a network. // Deitel package package com.deitel.advjhtp1.jmx.Printer; // java core package import java.util.Stack; public class PrinterSimulator implements Runnable { private private private private Stack printerStack boolean isOnline = boolean isPrinting boolean isPaperJam = new Stack(); true; = false; = false; Class PrinterSimulator 1. Declarations 2. Constructor

// 50 sheets of paper in tray private Integer paperInTray = new Integer( 50 ); // 100% full of ink private Integer tonerCartridge = new Integer( 100 ); private String currentPrintJob; private boolean isAlive = true; private PrinterEventListener eventListener; // default public constructor public PrinterSimulator( PrinterEventListener listener ) { eventListener = listener; }

Constructor takes PrinterEventListener as input


2001 Prentice Hall, Inc.
All rights reserved.

Outline
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 // stops execution of thread public void stop() { isAlive = false; } // main life-cycle of the printer. // prints one job from print job stack // 1) if offline, it pauses and waits. // 2) if online, handles one print job public void run() { // main loop within thread while ( isAlive ) { // pause if offline if ( !isOnline ) { synchronized ( this ) { // waits for printer become online try { wait(); } // if interrupt occurs catch ( InterruptedException exception ) { exception.printStackTrace(); System.exit( -1 ); } } // end synchronized } // end if 3. Simulate printer activities

2001 Prentice Hall, Inc.


All rights reserved.

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

// prints one job from print job stack startPrintingProcess(); } // end while } public void startPrintingProcess() { // warm up the printer, print top print job from print // stack and adjust paper values and toner values try { // warm up printer for incoming batch of print jobs Thread.sleep( 1000 * 5 ); if ( ( paperInTray.intValue() > 0 ) && ( tonerCartridge.intValue() > 10 ) && ( !isPaperJam ) ) { // start the printing process currentPrintJob = getNextPrintJob(); isPrinting = true; // 12 seconds to print a normal document Thread.sleep( 1000 * 12 ); // each print job uses 10 pages updatePaperInTray( paperInTray.intValue() - 10 ); updateToner(); updatePaperJam(); isPrinting = false; // make sure no references are left dangling currentPrintJob = null; } }

Outline
3. Simulate printer activities

Simulate printing process

2001 Prentice Hall, Inc.


All rights reserved.

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

// if interrupt occurs catch ( InterruptedException exception ) { exception.printStackTrace(); System.exit( -1 ); } } // end method startPrintingProcess // returns current printed job public String getCurrentPrintJob() { return currentPrintJob; } // is printer online? public Boolean isOnline() { return new Boolean ( isOnline ); } // update amount of paper in paper tray public synchronized void updatePaperInTray( int newValue ) { paperInTray = new Integer ( newValue ); // fire event if paper tray low if ( paperInTray.intValue() <= 0 ) { eventListener.outOfPaperEvent(); } } // is paper jammed? public Boolean isPaperJam() { return new Boolean( isPaperJam ); }

Outline
3. Simulate printer activities

Add paper to paper tray

2001 Prentice Hall, Inc.


All rights reserved.

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

// cancel pending print jobs public void cancelPendingPrintJobs() { synchronized ( printerStack ) { printerStack.clear(); } } // update amount of toner available in toner cartridge public synchronized void updateToner() { // after every print job, toner levels drop 1% tonerCartridge = new Integer ( tonerCartridge.intValue() - 1 ); // fire event if toner is low if ( tonerCartridge.intValue() <= 10 ) { eventListener.lowTonerEvent(); } } public synchronized void updatePaperJam() { if ( Math.random() > 0.9 ) { isPaperJam = true; eventListener.paperJamEvent(); } } // returns number of pages in paper tray public synchronized Integer getPaperTray() { return paperInTray; }

Outline
3. Simulate printer activities

Update toner in toner cartridge

Issue paper jam event randomly

2001 Prentice Hall, Inc.


All rights reserved.

Outline
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 // returns amount of toner in toner cartridge public synchronized Integer getToner() { return tonerCartridge; } // generates a random number of print jobs with varying IDs public void populatePrintStack() { int numOfJobs = ( int ) ( Math.random ( ) * 10 ) + 1; // generate print jobs synchronized ( printerStack ) { for ( int i = 0 ; i < numOfJobs ; i++ ) { printerStack.add ( "PRINT_JOB_ID #" + i ); } } } // returns next print job in stack, populating the stack // if it is empty public String getNextPrintJob() { if ( printerStack.isEmpty() ) { populatePrintStack ( ); // simulates absence of print jobs try { Thread.sleep ( ( int ) ( Math.random() * 1000 * 10 ) ); } 3. Simulate printer activities

Generate print jobs

2001 Prentice Hall, Inc.


All rights reserved.

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243

// if interrupt occurs catch ( InterruptedException exception ) { exception.printStackTrace() ; System.exit ( -1 ) ; } } // Remove topmost queued resource. String printJob; synchronized ( printerStack ) { printJob = ( String ) printerStack.pop(); } return printJob; } // end method getNextPrintJob // returns all jobs yet to be printed public String[] getPendingPrintJobs() { String[] pendingPrintJobs; // create array of pending print jobs synchronized ( printerStack ) { Object[] temp = printerStack.toArray() ; pendingPrintJobs = new String[ temp.length ] ;

Outline
3. Simulate printer activities

Get all jobs to be printed

for ( int i = 0 ; i < pendingPrintJobs.length ; i++ ) { pendingPrintJobs [ i ] = ( String )temp[ i ]; } } return pendingPrintJobs;

2001 Prentice Hall, Inc.


} // end method getPendingPrintJobs All rights reserved.

Outline
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 // sets printer status to online public void setOnline() { isOnline = true; // notify all waiting states synchronized ( this ) { notifyAll() ; } } // sets printer status to offline public void setOffline() { isOnline = false; } // replenishes amount of paper in paper tray to specified // value public void replenishPaperTray ( int paperStack ) { updatePaperInTray( paperStack ) ; } // is printer printing? public boolean isPrinting() { return isPrinting; } } 3. Simulate printer activities

When printer becomes online, notify all waiting states

2001 Prentice Hall, Inc.


All rights reserved.

24.3.2 Implementation of the JMX Management Agent JMX agent


MBean server MBeans (managed resource) Protocol adaptor or connector

2001 Prentice Hall, Inc. All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

// Fig. 22.8: PrinterManagementAgent.java // This application creates an MBeanServer and starts an RMI // connector MBean service. // deitel package package com.deitel.advjhtp1.jmx.PrinterManagement; // JMX core packages import javax.management.*; public class PrinterManagementAgent { public static void main( String[] args ) { ObjectInstance rmiConnectorServer = null; ObjectInstance printer = null; ObjectInstance broadcaster = null; ObjectName objectName = null; // create an MBeanServer Create MBeanServer server = MBeanServerFactory.createMBeanServer();

Outline
Class PrinterManagementAgent 1. main 1.1 create MBeanServer 1.2 create RMI connector server 1.3 create broadcaster MBean

MBean server

// create an RMI connector service, a printer simulator // MBean and a broadcaster MBean try { // create an RMI connector server rmiConnectorServer = server.createMBean ( "com.sun.jdmk.comm.RmiConnectorServer", null ); // create a broadcaster MBean String name = server.getDefaultDomain() + ":type=" + "PrinterEventBroadcaster"; String className = "com.deitel.advjhtp1.jmx." + "PrinterSimulator.PrinterEventBroadcaster"

Create RMI connector server

Create broaddcaster MBean


2001 Prentice Hall, Inc.
All rights reserved.

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

objectName = new ObjectName( name ); printer = server.createMBean( className, objectName ); // create a printer simulator MBean name = server.getDefaultDomain() + ":type=" + "Printer"; className = "com.deitel.advjhtp1.jmx." + "PrinterSimulator.Printer"; objectName = new ObjectName( name ); broadcaster = server.createMBean( className, objectName ); } // end try // handle class not JMX-compliant MBean exception catch ( NotCompliantMBeanException exception ) { exception.printStackTrace(); } // handle MBean constructor exception catch ( MBeanException exception ) { exception.printStackTrace(); } // handle MBean already exists exception catch ( InstanceAlreadyExistsException exception ) { exception.printStackTrace(); } // handle MBean constructor exception catch ( ReflectionException exception ) { exception.printStackTrace(); }

Outline
1.4 create printer simulator MBean 1.5 handle exceptions

Create printer simulator MBean

2001 Prentice Hall, Inc.


All rights reserved.

Outline
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 // handle invalid object name exception catch ( MalformedObjectNameException exception) { exception.printStackTrace(); } Specify // set port number Object[] parameter = new Object[ 1 ]; parameter[ 0 ] = new Integer( 5555 ); String[] signature = new String[ 1 ]; signature[ 0 ] = "int"; 1.6 specify RMI connector server port 1.7 set RMI connector server port 1.8 start RMI connector server

RMI connector server port

// invoke method setPort on RmiConnectorServer MBean // start the RMI connector service try { server.invoke( rmiConnectorServer.getObjectName(), "setPort", parameter, signature ); server.invoke( rmiConnectorServer.getObjectName(), "start" , new Object[ 0 ], new String[ 0 ] ); } // handle exception when executing method catch ( ReflectionException exception ) { exception.printStackTrace(); } // handle exception communicating with MBean catch ( MBeanException exception ) { exception.printStackTrace(); }

Set RMI connector server port Start RMI connector server

2001 Prentice Hall, Inc.


All rights reserved.

Outline

106 107 108 109 110 111 112

// handle exception if MBean not found catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } } // end method main }

____________________________________________________________________ Interface
PrinterEventBroadcasterMBean

1 2 3 4 5 6 7 8 9 10 11 12 13

// Fig. 22.9: PrinterEventBroadcasterMBean.java // This class defines the MBean interface. // deitel package package com.deitel.advjhtp1.jmx.PrinterSimulator; // JMX core packages import javax.management.Notification; public interface PrinterEventBroadcasterMBean { public void sendNotification( Notification notification ); }

1. Declarations

2001 Prentice Hall, Inc.


All rights reserved.

24.3.3 Broadcasting and Receiving Notifications Broadcast notifications


Notification broadcaster MBean

Receive notifications

2001 Prentice Hall, Inc. All rights reserved.

Outline
Class PrinterEventBroadcaster 1. Declarations

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

// Fig. 22.10: PrinterEventBroadcaster.java // This class defines an MBean that // provides events information. // deitel package package com.deitel.advjhtp1.jmx.PrinterSimulator; // JMX core packages import javax.management.MBeanNotificationInfo; import javax.management.NotificationBroadcasterSupport; // extends NotificationBroadcasterSupport to adopt its // functionality. public class PrinterEventBroadcaster extends NotificationBroadcasterSupport implements PrinterEventBroadcasterMBean { private static final String OUT_OF_PAPER = "PrinterEvent.OUT_OF_PAPER"; private static final String LOW_TONER = "PrinterEvent.LOW_TONER"; private static final String PAPER_JAM = "PrinterEvent.PAPER_JAM";

2001 Prentice Hall, Inc.


All rights reserved.

Outline
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 // provide information about deliverable events public MBeanNotificationInfo[] getNotificationInfo() { // array containing descriptor objects MBeanNotificationInfo[] descriptorArray = new MBeanNotificationInfo[ 1 ]; // different event types String[] notificationTypes = new String[ 3 ]; notificationTypes[ 0 ] = PrinterEventBroadcaster.OUT_OF_PAPER; notificationTypes[ 1 ] = PrinterEventBroadcaster.LOW_TONER; notificationTypes[ 2 ] = PrinterEventBroadcaster.PAPER_JAM; // notification class type String classType = "javax.management.Notification"; // description of MBeanNotificationInfo String description = "Notification types for PrinterEventBroadcaster"; // populate descriptor array descriptorArray[ 0 ] = new MBeanNotificationInfo( notificationTypes, classType, description ); return descriptorArray; } // end method getNotificationInfo } 2. Implement getNotificationInfo to describe events

Implement getNotificationInfo to describe events

Specify event types

Event description

2001 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

// Fig. 22.11: PrinterEventHandler.java // The class adds a listener to the broadcaster MBean and // defines the event handlers when event occurs. // deitel package package com.deitel.advjhtp1.jmx.Client; // JMX core packages import javax.management.*; // JDMK core packages import com.sun.jdmk.comm.RmiConnectorClient; import com.sun.jdmk.comm.ClientNotificationHandler; // Deitel packages import com.deitel.advjhtp1.jmx.Printer.*; public class PrinterEventHandler { private RmiConnectorClient rmiClient; private PrinterEventListener eventTarget; // notification listener annonymous inner class private NotificationListener notificationListener = new NotificationListener() { public void handleNotification( Notification notification, Object handback ) { // retrieve notification type String notificationType = notification.getType(); // handle different notifications if ( notificationType.equals( "PrinterEvent.OUT_OF_PAPER" ) ) { handleOutOfPaperEvent(); return; }

Outline
Class PrinterEventhandler

1. Inner class NotificationListener

Inner class NotificationListener

2001 Prentice Hall, Inc.


All rights reserved.

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

if ( notificationType.equals( "PrinterEvent.LOW_TONER" ) ) { handleLowTonerEvent(); return; } if ( notificationType.equals( "PrinterEvent.PAPER_JAM" ) ) { handlePaperJamEvent(); return; } } // end method handleNotification }; // end annonymous inner class // default constructor public PrinterEventHandler( RmiConnectorClient inputRmiClient, ManagerSidePrinterEventListener inputEventTarget ) { rmiClient = inputRmiClient; eventTarget = inputEventTarget;

Outline
2. Constructor 2.1 set notification mode 2.2 register listener to RMI connector client

Set notification mode

// set notification push mode rmiClient.setMode( ClientNotificationHandler.PUSH_MODE ); // register listener try { ObjectName objectName = new ObjectName( rmiClient.getDefaultDomain() + ":type=" + "PrinterEventBroadcaster" ); rmiClient.addNotificationListener( objectName, notificationListener, null, null ); }

Register listener to RMI connector client

2001 Prentice Hall, Inc.


All rights reserved.

Outline
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 // if MBean does not exist in the MBean server catch ( InstanceNotFoundException exception) { exception.printStackTrace(); } // if the format of the object name is wrong catch ( MalformedObjectNameException exception ) { exception.printStackTrace(); } } // end PrinterEventHandler constructor // delegate out of paper event private void handleOutOfPaperEvent() { eventTarget.outOfPaper(); } // delegate low toner event private void handleLowTonerEvent() { eventTarget.lowToner(); } // delegate paper jam event private void handlePaperJamEvent() { eventTarget.paperJam(); } } 3. Delegate printer events

Delegate printer events

2001 Prentice Hall, Inc.


All rights reserved.

24.3.4 Management Application Management application for the case study


GUI for managing the printer
ClientPrinterManagement ManagerSidePrinterEventListener PrinterManagementGUI

2001 Prentice Hall, Inc. All rights reserved.

Outline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 // Fig. 22.12: ClientPrinterManagement.java // This application establishes a connection to the MBeanServer // and creates an MBean for PrinterSimulator. // deitel package package com.deitel.advjhtp1.jmx.Client; // Java core packages import java.awt.*; import java.awt.event.*; // JMX core packages import javax.management.*; // JDMX core packages import com.sun.jdmk.comm.RmiConnectorClient; import com.sun.jdmk.comm.RmiConnectorAddress; public class ClientPrinterManagement { private RmiConnectorClient rmiClient; // instantiate client connection public ClientPrinterManagement() { // create connector client instance rmiClient = new RmiConnectorClient(); // create address instance RmiConnectorAddress rmiAddress = new RmiConnectorAddress(); Class ClientPrinterManagement 1. Constructor 1.1 get RMI connector client

Get RMI connector client

2001 Prentice Hall, Inc.


All rights reserved.

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

// specify port rmiAddress.setPort( 5555 ); // establish connection rmiClient.connect( rmiAddress ); } // end ClinetPrinterManagement constructor // return RmiConnectorClient reference public RmiConnectorClient getClient() { return rmiClient; } public static void main( String[] args ) { // instantiate client connection ClientPrinterManagement clientManager = new ClientPrinterManagement();

Set RMI client port Establish connection

Outline
1.2 set RMI client port 1.3 establish connection 2. Get RmiConnectorClient reference 3. main 3.1 invoke constructor 3.2 invoke GUI

// get RMIConnectorClient handle RmiConnectorClient client = clientManager.getClient(); // start GUI PrinterManagementGUI printerManagementGUI = new PrinterManagementGUI( client ); // display the output printerManagementGUI.setSize( new Dimension( 500, 500 ) ); printerManagementGUI.setVisible( true ); } // end method main }

Invoke GUI

2001 Prentice Hall, Inc.


All rights reserved.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

// Fig. 22.14: PrinterManagementGUI.java // This class defines the GUI for the // printer management application. // deitel package package com.deitel.advjhtp1.jmx.Client; // Java AWT core package import java.awt.*; import java.awt.event.*; // Java standard extensions import javax.swing.*; // JMX core packages import javax.management.*; // JDMX core packages import com.sun.jdmk.comm.RmiConnectorClient; import com.sun.jdmk.comm.RmiConnectorAddress; // Deitel packages import com.deitel.advjhtp1.jmx.Printer.*; public class PrinterManagementGUI extends JFrame implements PrinterEventListener { // TextAppender appends text to a JTextArea. This Runnable // object should be executed only using SwingUtilities // methods invokeLater or invokeAndWait as it modifies // a live Swing component. private class TextAppender implements Runnable { private String text; private JTextArea textArea;

Outline
Class PrinterManagementGUI 1. Import packages 2. Inner class TextAppender

Inner class TextAppender


2001 Prentice Hall, Inc.
All rights reserved.

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

// TextAppender constructor public TextAppender( JTextArea area, String newText ) { text = newText; textArea = area; } // display new text in JTextArea public void run() { // append new message textArea.append( text ); // move caret to end of messageArea to ensure new // message is visible on screen textArea.setCaretPosition( textArea.getText().length() ); } } // end TextAppender inner class private private private private ObjectName objectName; RmiConnectorClient client; JTextArea printerStatusTextArea = new JTextArea(); JTextArea printerEventTextArea = new JTextArea();

Outline
3. Constructor 3.1 define status panel

public PrinterManagementGUI( RmiConnectorClient rmiClient ) { super( "JMX Printer Management Example" ); Container container = getContentPane(); // status panel JPanel printerStatusPanel = new JPanel(); printerStatusPanel.setPreferredSize( new Dimension( 512, 200 ) );

Define status panel


2001 Prentice Hall, Inc.
All rights reserved.

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

JScrollPane statusScrollPane = new JScrollPane(); statusScrollPane.setAutoscrolls( true ); statusScrollPane.setPreferredSize( new Dimension( 400, 150 ) ); statusScrollPane.getViewport().add( printerStatusTextArea, null ); printerStatusPanel.add( statusScrollPane, null ); // buttons panel JPanel buttonPanel = new JPanel(); buttonPanel.setPreferredSize( new Dimension( 512, 200 ) ); // define action for Check Status button JButton checkStatusButton = new JButton( "Check Status" ); checkStatusButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { checkStatusButtonAction( event ); } } ); // define action for Add Paper button JButton addPaperButton = new JButton( "Add Paper" ); addPaperButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { addPaperButtonAction( event ); } } );

Outline
3.2 define buttons panel 3.2.1 define actions for the buttons

Define buttons panel

Define actions for the buttons

2001 Prentice Hall, Inc.


All rights reserved.

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

// define action for Cancel Pending Print Jobs button JButton cancelPendingPrintJobsButton = new JButton( "Cancel Pending Print Jobs" ); cancelPendingPrintJobsButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { cancelPendingPrintJobsButtonAction( event ); } } ); // add three buttons to the panel buttonPanel.add( checkStatusButton, null ); buttonPanel.add( addPaperButton, null ); buttonPanel.add( cancelPendingPrintJobsButton, null ); // events panel JPanel printerEventPanel = new JPanel(); printerEventPanel.setPreferredSize( new Dimension( 512, 200) ); JScrollPane eventsScrollPane = new JScrollPane(); eventsScrollPane.setAutoscrolls( true ); eventsScrollPane.setPreferredSize( new Dimension( 400, 150 ) ); eventsScrollPane.getViewport().add( printerEventTextArea, null ); printerEventPanel.add( eventsScrollPane, null );

Outline
Define actions for the buttons
3.3 define events panel

Define events panel

// initialize the text printerStatusTextArea.setText( "Printer Status: ---\n" ); printerEventTextArea.setText( "Events: --- \n" ); // put all the container.add( container.add( container.add( panels together printerStatusPanel, BorderLayout.NORTH ); printerEventPanel, BorderLayout.SOUTH ); buttonPanel, BorderLayout.CENTER );

2001 Prentice Hall, Inc.


All rights reserved.

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

// set RmiConnectorClient reference client = rmiClient; // invoke method startPrinting of the // PrinterSimulator MBean try { String name = client.getDefaultDomain() + ":type=" + "Printer"; objectName = new ObjectName( name ); client.invoke( objectName, "startPrinting", new Object[ 0 ], new String[ 0 ] ); }

Outline
Start printing via MBean
3.4 start printer simulator 3.5 get PrinterEventHandler

// invalid object name catch ( MalformedObjectNameException exception ) { exception.printStackTrace(); } // if cannot invoke the method catch ( ReflectionException exception) { exception.printStackTrace(); } // if invoked method throws exception catch ( MBeanException exception ) { exception.printStackTrace(); } // if MBean is not registered with MBean server catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } // instantiate PrinterEventNotifier PrinterEventHandler printerEventHandler = new PrinterEventHandler( client, this );

Get PrinterEventHandler
2001 Prentice Hall, Inc.
All rights reserved.

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

// unregister MBean when close the window addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent event ) { // unregister MBean try { // unregister the PrinterSimulator MBean client.unregisterMBean( objectName ); // unregister the PrinterEventBroadcaster // MBean String name = client.getDefaultDomain() + ":type=" + "PrinterEventBroadcaster"; objectName = new ObjectName( name ); client.unregisterMBean( objectName ); } // if invalid object name catch ( MalformedObjectNameException exception) { exception.printStackTrace(); } // if exception is caught from method preDeregister catch ( MBeanRegistrationException exception ) { exception.printStackTrace(); } // if MBean is not registered with MBean server catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); }

Outline
3.6 define actions when close window

Unregister Mbeans when close window

2001 Prentice Hall, Inc.


All rights reserved.

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252

// terminate the program System.exit( 0 ); } // end method windowClosing } // end WindowAdapter constructor ); // end addWindowListener } // end PrinterManagementGUI constructor // out of paper events public void outOfPaper() { SwingUtilities.invokeLater( new TextAppender( printerEventTextArea, "\nEVENT: Out of Paper!\n" ) ); } // toner low events public void lowToner() { SwingUtilities.invokeLater( new TextAppender( printerEventTextArea, "\nEVENT: Toner Low!\n" ) ); } // paper jam events public void paperJam() { SwingUtilities.invokeLater( new TextAppender( printerEventTextArea, "\nEVENT: Paper Jam!\n" ) ); }

Outline
4 display events in events panel

Display events

2001 Prentice Hall, Inc.


All rights reserved.

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

// add paper to the paper tray public void addPaperButtonAction( ActionEvent event ) { try { client.invoke( objectName, "replenishPaperTray", new Object[ 0 ], new String[ 0 ] ); } // if cannot invoke the method catch ( ReflectionException exception) { exception.printStackTrace(); } // if invoked method throws exception catch ( MBeanException exception ) { exception.printStackTrace(); } // if MBean is not registered with MBean server catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } } // end method addPaperButtonAction

Outline
5. Add paper to printer 6. Cancel pending print jobs

Add paper to paper try when click Add Paper button

// cancel pending print jobs public void cancelPendingPrintJobsButtonAction( ActionEvent event ) { try { client.invoke( objectName, "cancelPendingPrintJobs", new Object[ 0 ], new String[ 0 ] ); }

Cancel pending print jobs when click Cancel Pending Print Jobs button

2001 Prentice Hall, Inc.


All rights reserved.

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

Outline
// if cannot invoke the method catch ( ReflectionException exception) { exception.printStackTrace(); } // if invoked method throws exception catch ( MBeanException exception ) { exception.printStackTrace(); } // if MBean is not registered with MBean server catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } } // end method cancelPendingPrintJobsButtonAction public void checkStatusButtonAction( ActionEvent event ) { Object onlineResponse = null; Object paperJamResponse = null; Object printingResponse = null; Object paperTrayResponse = null; Object pendingPrintJobsResponse = null; // manage printer remotely try { // check if the printer is on line onlineResponse = client.invoke( objectName, "isOnline", new Object[ 0 ], new String[ 0 ] ); 7. Check printers status 7.1 get printers status

Check printers status when click Check Status button

2001 Prentice Hall, Inc.


All rights reserved.

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

// check if the printer is paper jammed paperJamResponse = client.invoke( objectName, "isPaperJam", new Object[ 0 ], new String[ 0 ] ); // check if the printing is pringint printingResponse = client.invoke( objectName, "isPrinting", new Object[ 0 ], new String[ 0 ] ); // get the paper tray paperTrayResponse = client.invoke( objectName, "getPaperTray", new Object[ 0 ], new String[ 0 ] ); // get pending print jobs pendingPrintJobsResponse = client.invoke( objectName, "getPendingPrintJobs" , new Object[ 0 ], new String[ 0 ] ); } // if cannot invoke the method catch ( ReflectionException exception ) { exception.printStackTrace(); } // if invoked method throws exception catch ( MBeanException exception ) { exception.printStackTrace(); } // if MBean is not registered with MBean server catch ( InstanceNotFoundException exception ) { exception.printStackTrace(); } // status for the online condition boolean isOnline = ( ( Boolean ) onlineResponse ).booleanValue();

Outline
7.2 prepare output

Check printers status by calling methods on Printer MBean

2001 Prentice Hall, Inc.


All rights reserved.

Outline
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 // display status if ( isOnline ) { SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "\nPrinter is ONLINE.\n" ) ); } else { SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "\nPrinter is OFFLINE.\n" ) ); } // status for the paper jam condition boolean isPaperJam = ( ( Boolean ) paperJamResponse ).booleanValue(); // display status if ( isPaperJam ) { SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "Paper jammed.\n" ) ); } else { SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "No Paper Jam.\n" ) ); } // status for the printing condition boolean isPrinting = ( ( Boolean )printingResponse ).booleanValue(); 7.2 prepare output

Append printer status to output area

2001 Prentice Hall, Inc.


All rights reserved.

391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

// display status if ( isPrinting ) { SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "Printer is currently printing.\n" ) ); } else { SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "Printer is not printing.\n" ) ); } // status for paper tray condition int paperRemaining = ( ( Integer )paperTrayResponse ).intValue(); // display status SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "Printer paper tray has " + paperRemaining + " pages remaining.\n" ) ); // status for pending print jobs Object[] pendingPrintJobs = ( Object[] ) pendingPrintJobsResponse; int pendingPrintJobsNumber = pendingPrintJobs.length; // display status SwingUtilities.invokeLater( new TextAppender( printerStatusTextArea, "Number of pending print jobs: " + pendingPrintJobsNumber + "\n" ) );

Outline
7.2 prepare output

Append printer status to output area

} // end method checkStatusButtonAction }

2001 Prentice Hall, Inc.


All rights reserved.

22.3.5 Compiling and Running the example CLASSPATH


jdmkrt.jar and jdmktk.jar

Compile
Files in package com.deitel.advjhtp1.jmx.PrinterManagement Files in package com.deitel.advjhtp1.jmx.PrinterSimulator

Run
PrinterManagementAgent ClientPrinterManagement

2001 Prentice Hall, Inc. All rights reserved.

Outline
Program output

Initial window

2001 Prentice Hall, Inc.


All rights reserved.

Outline
Program output

Status after out-of-paper event happened

Out-of-paper event happened

2001 Prentice Hall, Inc.


All rights reserved.

Outline
Program output

Status after clicked Add Paper button

2001 Prentice Hall, Inc.


All rights reserved.

Outline
Program output

Status after out-of-paper event happened

Out-of-paper event happened

2001 Prentice Hall, Inc.


All rights reserved.

Outline
Program output

Status after clicked Cancel Pending Print Jobs button

2001 Prentice Hall, Inc.


All rights reserved.

Вам также может понравиться