 2001 Prentice Hall, Inc. All rights reserved. Chapter 24 – Java Management Extensions (JMX) Outline 24.1Introduction 24.2Installation 24.3Case Study.

Slides:



Advertisements
Similar presentations
Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
Java threads Threaded class extends thread Synchronized class is a monitor Runnable interface gives thread methods All code is (C) Copyright 1999 by Deitel.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Io package as Java’s basic I/O system continue’d.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 25 - Jiro Outline 25.1 Introduction 25.2 Installation 25.3 Starting Jiro 25.4 Dynamic vs. Static.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
LAB 1CSIS04021 Briefing on Assignment One & RMI Programming February 13, 2007.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 19.1 Test-Driving the Shipping Hub Application.
 2002 Prentice Hall, Inc. All rights reserved. Introduction Concurrency normally available in OS primitives Java provides built-in multithreading –Multithreading.
Chapter 12 1 TOPIC 13B l Buttons and Action Listeners Window Interfaces Using Swing Objects.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Li Tak Sing COMPS311F. RMI callbacks In previous example, only the client can initiate a communication with the server. The server can only response to.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaBeans and.
Java Management Extensions (JMX) Jmx Introduction.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Graphics in Java Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Advanced Programming, Based on LY Stefanus’s slides slide 7.1 Multithreading : Using the Runnable interface.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 10.1 Test-Driving the Interest Calculator.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 16 – Multithreading Outline 16.1 Introduction 16.2 Thread States: Life Cycle of a Thread 16.3.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 – Methods Part I.
UMBC Distributed Computing with Objects RMI/Corba CMSC 432 Shon Vick.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 28.1 Java Speech API 28.2 Downloading and.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
Li Tak Sing COMPS311F. Case study: a multithreaded chat server The source contains 3 files: ChatServer //the chat server ChatThread //the thread on the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
CompSci 230 S Programming Techniques
Chapter 14 – Exception Handling
Threads in Java Two ways to start a thread
Ellen Walker Hiram College
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Introduction to Event Handling
Events, Event Handlers, and Threads
Chapter 15 – Exception Handling
Presentation transcript:

 2001 Prentice Hall, Inc. All rights reserved. Chapter 24 – Java Management Extensions (JMX) Outline 24.1Introduction 24.2Installation 24.3Case Study Instrument Resources Implement the JMX Management Agent Broadcasting and Receiving Notifications Management Application Compiling and Running the example 24.4Internet and World Wide Web Resources

 2001 Prentice Hall, Inc. All rights reserved 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 Introduction JMX provides –Platform-independence –Protocol-independence –Reusable –Intelligent agent –Scalability

 2001 Prentice Hall, Inc. All rights reserved Introduction Management Application Java Dynamic Management Agent Managed Resource Instrumentation Level Agent Level Manager Level

 2001 Prentice Hall, Inc. All rights reserved Installation Implementation of JMX –Java Dynamic Management Kit (JDMK) Download JDMK – Set CLASSPATH –jdmkrt.jar and jdmktk.jar

 2001 Prentice Hall, Inc. All rights reserved Case Study Management solution –Resource –Agent –Application MBean MBean server

 2001 Prentice Hall, Inc. All rights reserved Case Study Printer MBean RmiConnectorClient: 5555 RmiConnectorServer: 5555 MBeanServer PrinterEventBroadcaster MBean PrinterSimulator Management Application

 2001 Prentice Hall, Inc. All rights reserved 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 Instrument Resources MBean class design pattern –Implement MBean interface –Public and concrete –Public constructor

 2001 Prentice Hall, Inc. All rights reserved. Outline Interface PrinterMBean 1. Declarations 1 // Fig. 22.3: PrinterMBean.java 2 // This class specifies the interface that will be implemented 3 // by Printer, which will function as an MBean. 4 5 // deitel package 6 package com.deitel.advjhtp1.jmx.PrinterSimulator; 7 8 public interface PrinterMBean { 9 10 // is it printing? 11 public Boolean isPrinting(); // is it online? 14 public Boolean isOnline(); // is paper jammed? 17 public Boolean isPaperJam(); // returns paper amount in tray 20 public Integer getPaperTray(); // returns ink level in toner cartridge 23 public Integer getToner(); // returns ID of print job that is currently printing 26 public String getCurrentPrintJob(); // returns array of all queued up print jobs 29 public String [] getPendingPrintJobs(); // sets availability status of printer 32 public void setOnline ( Boolean online ); 33 Management interface Interface name with MBean suffix Return value is serializable is, get, set methods

 2001 Prentice Hall, Inc. All rights reserved. Outline Interface PrinterEventListener 34 // fills up paper tray again with paper 35 public void replenishPaperTray(); // cancel pending print jobs 38 public void cancelPendingPrintJobs(); // start printing process 41 public void startPrinting(); 42 } 1 // Fig. 22.4: PrinterEventListener.java 2 // The listener interface for printer events. 3 4 // Deitel package 5 package com.deitel.advjhtp1.jmx.Printer; 6 7 public interface PrinterEventListener { 8 9 public void outOfPaper(); public void lowToner(); public void paperJam(); 14 } operations

 2001 Prentice Hall, Inc. All rights reserved. Outline Class Printer 1. Declarations 2. Constructor 2.1 connect to printer device 1 // Fig. 22.5: Printer.java 2 // This class provides implementation for PrinterMBean 3 // interface and registers a managing MBean for the Printer 4 // device, which is simulated by PrinterSimulator.java. 5 6 // deitel package 7 package com.deitel.advjhtp1.jmx.PrinterSimulator; 8 9 // Java core package 10 import java.lang.Thread; 11 import java.util.ArrayList; // JMX core packages 14 import javax.management.*; // Deitel packages 17 import com.deitel.advjhtp1.jmx.Printer.*; public class Printer implements PrinterMBean, 20 PrinterEventListener { private PrinterSimulator printerSimulator; 23 private static final int PAPER_STACK_SIZE = 50; 24 private ObjectInstance eventBroadcasterInstance; 25 private ObjectName eventBroadcasterName; 26 private ObjectName printerName; 27 private MBeanServer mBeanServer; public Printer() 30 { 31 // connect to the printer device 32 printerSimulator = new PrinterSimulator( this ) ; 33 Thread myThread = new Thread( printerSimulator ) ; 34 myThread.start(); 35 Connect to printer device MBean class implements responding MBean interface Public constructor

 2001 Prentice Hall, Inc. All rights reserved. Outline 2.2 find MBean servers 2.3 specify MBean server requirement 2.4 identify MBean server 36 // find all MBean servers in current JVM 37 ArrayList arrayList = 38 MBeanServerFactory.findMBeanServer( null ); // retrieve the MBeanServer reference 41 if ( arrayList.size() == 0) 42 System.out.println( "Cannot find a MBeanServer!" ); else { // get the MBeanServer that has the 47 // PrinterEventBroadcaster MBean registered with it 48 for ( int i = 0; i < arrayList.size(); i++ ) { 49 MBeanServer foundMBeanServer = 50 ( MBeanServer )arrayList.get( i ); // obtain the object name for the 53 // PrinterEventBroadcaster MBean 54 try { 55 String name = foundMBeanServer.getDefaultDomain() 56 + ":type=" + "PrinterEventBroadcaster"; 57 eventBroadcasterName = new ObjectName( name ); 58 } // handle exception when creating ObjectName 61 catch ( MalformedObjectNameException exception ) { 62 exception.printStackTrace(); 63 } // check whether the PrinterEventBroadcaster MBean is 66 // registered with this MBeanServer 67 if ( foundMBeanServer.isRegistered( 68 eventBroadcasterName ) ) { 69 mBeanServer = foundMBeanServer; 70 break; 71 } Find MBean servers Specify MBean server requirement Identify MBean server

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Implement management solution } // end for loop } // end if-else to get the MBeanServer reference } // end PrinterSimulator constructor // will stop the printer thread from executing 80 // once execution should stop. 81 public void stop() 82 { 83 printerSimulator.stop(); 84 } // Is it printing? 87 public Boolean isPrinting() 88 { 89 return new Boolean( printerSimulator.isPrinting() ); 90 } // is online? 93 public Boolean isOnline() 94 { 95 return printerSimulator.isOnline(); 96 } // is paper jammed? 99 public Boolean isPaperJam() 100 { 101 return printerSimulator.isPaperJam(); 102 } // is paper tray empty? 105 public Integer getPaperTray() 106 { 107 return printerSimulator.getPaperTray(); 108 }

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Implement management solution // is toner low? 111 public Integer getToner() 112 { 113 return printerSimulator.getToner(); 114 } // returns ID of print job that is currently printing 117 public String getCurrentPrintJob() 118 { 119 return printerSimulator.getCurrentPrintJob(); 120 } // returns array of all queued up print jobs 123 public String[] getPendingPrintJobs() 124 { 125 return printerSimulator.getPendingPrintJobs(); 126 } // sets status availability of printer 129 public void setOnline( Boolean online ) 130 { 131 if ( online.booleanValue() == true ) 132 printerSimulator.setOnline(); 133 else 134 printerSimulator.setOffline(); 135 } // fills up the paper tray again with paper. 138 public void replenishPaperTray() 139 { 140 printerSimulator.replenishPaperTray ( 141 Printer.PAPER_STACK_SIZE ); 142 } 143

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

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

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

 2001 Prentice Hall, Inc. All rights reserved. Outline 6.2 send notification 243 // handle exception communicating with MBean 244 catch( MBeanException exception ) { 245 exception.printStackTrace(); 246 } // handle exception if MBean not found 249 catch( InstanceNotFoundException exception ) { 250 exception.printStackTrace(); 251 } } // end method paperJamEvent // interface implementation 256 public void outOfPaper() 257 { 258 // delegate call 259 fireOutOfPaperEvent(); 260 } // interface implementation 263 public void lowToner() 264 { 265 // delegate call 266 fireLowTonerEvent(); 267 } // interface implementation 270 public void paperJam() 271 { 272 // delegate call 273 firePaperJamEvent(); 274 } 275 } Interface implementation

 2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterSimulator 1. Declarations 2. Constructor 1 // Fig. 22.6: PrinterSimulator.java 2 // This class simulates a printer device on a network. 3 4 // Deitel package 5 package com.deitel.advjhtp1.jmx.Printer; 6 7 // java core package 8 import java.util.Stack; 9 10 public class PrinterSimulator implements Runnable { private Stack printerStack = new Stack(); 13 private boolean isOnline = true; 14 private boolean isPrinting = false; 15 private boolean isPaperJam = false; // 50 sheets of paper in tray 18 private Integer paperInTray = new Integer( 50 ); // 100% full of ink 21 private Integer tonerCartridge = new Integer( 100 ); private String currentPrintJob; 24 private boolean isAlive = true; 25 private PrinterEventListener eventListener; // default public constructor 28 public PrinterSimulator( 29 PrinterEventListener listener ) 30 { 31 eventListener = listener; 32 } 33 Constructor takes PrinterEventListener as input

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

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Simulate printer activities 68 // prints one job from print job stack 69 startPrintingProcess(); } // end while 72 } public void startPrintingProcess() 75 { 76 // warm up the printer, print top print job from print 77 // stack and adjust paper values and toner values 78 try { 79 // warm up printer for incoming batch of print jobs 80 Thread.sleep( 1000 * 5 ); if ( ( paperInTray.intValue() > 0 ) && 83 ( tonerCartridge.intValue() > 10 ) && 84 ( !isPaperJam ) ) { // start the printing process 87 currentPrintJob = getNextPrintJob(); 88 isPrinting = true; // 12 seconds to print a normal document 91 Thread.sleep( 1000 * 12 ); // each print job uses 10 pages 94 updatePaperInTray( paperInTray.intValue() - 10 ); 95 updateToner(); 96 updatePaperJam(); 97 isPrinting = false; // make sure no references are left dangling 100 currentPrintJob = null; 101 } 102 } Simulate printing process

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Simulate printer activities // if interrupt occurs 105 catch ( InterruptedException exception ) { 106 exception.printStackTrace(); 107 System.exit( -1 ); 108 } } // end method startPrintingProcess // returns current printed job 113 public String getCurrentPrintJob() 114 { 115 return currentPrintJob; 116 } // is printer online? 119 public Boolean isOnline() 120 { 121 return new Boolean ( isOnline ); 122 } // update amount of paper in paper tray 125 public synchronized void updatePaperInTray( int newValue ) 126 { 127 paperInTray = new Integer ( newValue ); // fire event if paper tray low 130 if ( paperInTray.intValue() <= 0 ) { 131 eventListener.outOfPaperEvent(); 132 } 133 } // is paper jammed? 136 public Boolean isPaperJam() 137 { 138 return new Boolean( isPaperJam ); 139 } Add paper to paper tray

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Simulate printer activities // cancel pending print jobs 142 public void cancelPendingPrintJobs() 143 { 144 synchronized ( printerStack ) { 145 printerStack.clear(); 146 } 147 } // update amount of toner available in toner cartridge 150 public synchronized void updateToner() 151 { 152 // after every print job, toner levels drop 1% 153 tonerCartridge = new Integer ( 154 tonerCartridge.intValue() - 1 ); // fire event if toner is low 157 if ( tonerCartridge.intValue() <= 10 ) { 158 eventListener.lowTonerEvent(); 159 } 160 } public synchronized void updatePaperJam() 163 { 164 if ( Math.random() > 0.9 ) { 165 isPaperJam = true; 166 eventListener.paperJamEvent(); 167 } 168 } // returns number of pages in paper tray 171 public synchronized Integer getPaperTray() 172 { 173 return paperInTray; 174 } 175 Update toner in toner cartridge Issue paper jam event randomly

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

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Simulate printer activities 208 // if interrupt occurs 209 catch ( InterruptedException exception ) { 210 exception.printStackTrace() ; 211 System.exit ( -1 ) ; 212 } 213 } // Remove topmost queued resource. 216 String printJob; synchronized ( printerStack ) { 219 printJob = ( String ) printerStack.pop(); 220 } return printJob; } // end method getNextPrintJob // returns all jobs yet to be printed 227 public String[] getPendingPrintJobs() 228 { 229 String[] pendingPrintJobs; // create array of pending print jobs 232 synchronized ( printerStack ) { 233 Object[] temp = printerStack.toArray() ; 234 pendingPrintJobs = new String[ temp.length ] ; for ( int i = 0 ; i < pendingPrintJobs.length ; i++ ) { 237 pendingPrintJobs [ i ] = ( String )temp[ i ]; 238 } 239 } return pendingPrintJobs; } // end method getPendingPrintJobs Get all jobs to be printed

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Simulate printer activities // sets printer status to online 246 public void setOnline() 247 { 248 isOnline = true; // notify all waiting states 251 synchronized ( this ) { 252 notifyAll() ; 253 } 254 } // sets printer status to offline 257 public void setOffline() 258 { 259 isOnline = false; 260 } // replenishes amount of paper in paper tray to specified 263 // value 264 public void replenishPaperTray ( int paperStack ) 265 { 266 updatePaperInTray( paperStack ) ; 267 } // is printer printing? 270 public boolean isPrinting() 271 { 272 return isPrinting; 273 } 274 } When printer becomes online, notify all waiting states

 2001 Prentice Hall, Inc. All rights reserved Implementation of the JMX Management Agent JMX agent –MBean server –MBeans (managed resource) –Protocol adaptor or connector

 2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterManagementAgent 1. main 1.1 create MBeanServer 1.2 create RMI connector server 1.3 create broadcaster MBean 1 // Fig. 22.8: PrinterManagementAgent.java 2 // This application creates an MBeanServer and starts an RMI 3 // connector MBean service. 4 5 // deitel package 6 package com.deitel.advjhtp1.jmx.PrinterManagement; 7 8 // JMX core packages 9 import javax.management.*; public class PrinterManagementAgent { public static void main( String[] args ) 14 { 15 ObjectInstance rmiConnectorServer = null; 16 ObjectInstance printer = null; 17 ObjectInstance broadcaster = null; 18 ObjectName objectName = null; // create an MBeanServer 21 MBeanServer server = 22 MBeanServerFactory.createMBeanServer(); // create an RMI connector service, a printer simulator 25 // MBean and a broadcaster MBean 26 try { // create an RMI connector server 29 rmiConnectorServer = server.createMBean ( 30 "com.sun.jdmk.comm.RmiConnectorServer", null ); // create a broadcaster MBean 33 String name = server.getDefaultDomain() 34 + ":type=" + "PrinterEventBroadcaster"; 35 String className = "com.deitel.advjhtp1.jmx." 36 + "PrinterSimulator.PrinterEventBroadcaster" Create MBean serverCreate RMI connector serverCreate broaddcaster MBean

 2001 Prentice Hall, Inc. All rights reserved. Outline 1.4 create printer simulator MBean 1.5 handle exceptions objectName = new ObjectName( name ); 39 printer = server.createMBean( 40 className, objectName ); // create a printer simulator MBean 43 name = server.getDefaultDomain() 44 + ":type=" + "Printer"; 45 className = "com.deitel.advjhtp1.jmx." 46 + "PrinterSimulator.Printer"; objectName = new ObjectName( name ); 49 broadcaster = server.createMBean( 50 className, objectName ); } // end try // handle class not JMX-compliant MBean exception 55 catch ( NotCompliantMBeanException exception ) { 56 exception.printStackTrace(); 57 } // handle MBean constructor exception 60 catch ( MBeanException exception ) { 61 exception.printStackTrace(); 62 } // handle MBean already exists exception 65 catch ( InstanceAlreadyExistsException exception ) { 66 exception.printStackTrace(); 67 } // handle MBean constructor exception 70 catch ( ReflectionException exception ) { 71 exception.printStackTrace(); 72 } Create printer simulator MBean

 2001 Prentice Hall, Inc. All rights reserved. Outline 1.6 specify RMI connector server port 1.7 set RMI connector server port 1.8 start RMI connector server // handle invalid object name exception 75 catch ( MalformedObjectNameException exception) { 76 exception.printStackTrace(); 77 } // set port number 80 Object[] parameter = new Object[ 1 ]; 81 parameter[ 0 ] = new Integer( 5555 ); 82 String[] signature = new String[ 1 ]; 83 signature[ 0 ] = "int"; // invoke method setPort on RmiConnectorServer MBean 86 // start the RMI connector service 87 try { 88 server.invoke( 89 rmiConnectorServer.getObjectName(), "setPort", 90 parameter, signature ); 91 server.invoke( 92 rmiConnectorServer.getObjectName(), "start", 93 new Object[ 0 ], new String[ 0 ] ); 94 } // handle exception when executing method 97 catch ( ReflectionException exception ) { 98 exception.printStackTrace(); 99 } // handle exception communicating with MBean 102 catch ( MBeanException exception ) { 103 exception.printStackTrace(); 104 } 105 Specify RMI connector server port Set RMI connector server port Start RMI connector server

 2001 Prentice Hall, Inc. All rights reserved. Outline Interface PrinterEventBroadcasterMBean 1. Declarations 106 // handle exception if MBean not found 107 catch ( InstanceNotFoundException exception ) { 108 exception.printStackTrace(); 109 } } // end method main 112 } ____________________________________________________________________ 1 // Fig. 22.9: PrinterEventBroadcasterMBean.java 2 // This class defines the MBean interface. 3 4 // deitel package 5 package com.deitel.advjhtp1.jmx.PrinterSimulator; 6 7 // JMX core packages 8 import javax.management.Notification; 9 10 public interface PrinterEventBroadcasterMBean { public void sendNotification( Notification notification ); 13 }

 2001 Prentice Hall, Inc. All rights reserved Broadcasting and Receiving Notifications Broadcast notifications –Notification broadcaster MBean Receive notifications

 2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterEventBroadcaster 1. Declarations 1 // Fig : PrinterEventBroadcaster.java 2 // This class defines an MBean that 3 // provides events information. 4 5 // deitel package 6 package com.deitel.advjhtp1.jmx.PrinterSimulator; 7 8 // JMX core packages 9 import javax.management.MBeanNotificationInfo; 10 import javax.management.NotificationBroadcasterSupport; // extends NotificationBroadcasterSupport to adopt its 13 // functionality. 14 public class PrinterEventBroadcaster 15 extends NotificationBroadcasterSupport 16 implements PrinterEventBroadcasterMBean { private static final String OUT_OF_PAPER = 19 "PrinterEvent.OUT_OF_PAPER"; 20 private static final String LOW_TONER = 21 "PrinterEvent.LOW_TONER"; 22 private static final String PAPER_JAM = 23 "PrinterEvent.PAPER_JAM"; 24

 2001 Prentice Hall, Inc. All rights reserved. Outline 2. Implement getNotificationInfo to describe events 25 // provide information about deliverable events 26 public MBeanNotificationInfo[] getNotificationInfo() 27 { 28 // array containing descriptor objects 29 MBeanNotificationInfo[] descriptorArray = 30 new MBeanNotificationInfo[ 1 ]; // different event types 33 String[] notificationTypes = new String[ 3 ]; 34 notificationTypes[ 0 ] = 35 PrinterEventBroadcaster.OUT_OF_PAPER; 36 notificationTypes[ 1 ] = 37 PrinterEventBroadcaster.LOW_TONER; 38 notificationTypes[ 2 ] = 39 PrinterEventBroadcaster.PAPER_JAM; // notification class type 42 String classType = "javax.management.Notification"; // description of MBeanNotificationInfo 45 String description = 46 "Notification types for PrinterEventBroadcaster"; // populate descriptor array 49 descriptorArray[ 0 ] = new MBeanNotificationInfo( 50 notificationTypes, classType, description ); return descriptorArray; } // end method getNotificationInfo 55 } Implement getNotificationInfo to describe events Event description Specify event types

 2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterEventhandler 1. Inner class NotificationListener 1 // Fig : PrinterEventHandler.java 2 // The class adds a listener to the broadcaster MBean and 3 // defines the event handlers when event occurs. 4 5 // deitel package 6 package com.deitel.advjhtp1.jmx.Client; 7 8 // JMX core packages 9 import javax.management.*; // JDMK core packages 12 import com.sun.jdmk.comm.RmiConnectorClient; 13 import com.sun.jdmk.comm.ClientNotificationHandler; // Deitel packages 16 import com.deitel.advjhtp1.jmx.Printer.*; public class PrinterEventHandler { private RmiConnectorClient rmiClient; 21 private PrinterEventListener eventTarget; // notification listener annonymous inner class 24 private NotificationListener notificationListener = 25 new NotificationListener() { 26 public void handleNotification( 27 Notification notification, Object handback ) 28 { 29 // retrieve notification type 30 String notificationType = notification.getType(); // handle different notifications 33 if ( notificationType.equals( 34 "PrinterEvent.OUT_OF_PAPER" ) ) { 35 handleOutOfPaperEvent(); 36 return; 37 } Inner class NotificationListener

 2001 Prentice Hall, Inc. All rights reserved. Outline 2. Constructor 2.1 set notification mode 2.2 register listener to RMI connector client 39 if ( notificationType.equals( 40 "PrinterEvent.LOW_TONER" ) ) { 41 handleLowTonerEvent(); 42 return; 43 } if ( notificationType.equals( 46 "PrinterEvent.PAPER_JAM" ) ) { 47 handlePaperJamEvent(); 48 return; 49 } } // end method handleNotification }; // end annonymous inner class // default constructor 56 public PrinterEventHandler( 57 RmiConnectorClient inputRmiClient, 58 ManagerSidePrinterEventListener inputEventTarget ) 59 { 60 rmiClient = inputRmiClient; 61 eventTarget = inputEventTarget; // set notification push mode 64 rmiClient.setMode( ClientNotificationHandler.PUSH_MODE ); // register listener 67 try { 68 ObjectName objectName = new ObjectName( 69 rmiClient.getDefaultDomain() 70 + ":type=" + "PrinterEventBroadcaster" ); rmiClient.addNotificationListener( objectName, 73 notificationListener, null, null ); 74 } Set notification modeRegister listener to RMI connector client

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Delegate printer events // if MBean does not exist in the MBean server 77 catch ( InstanceNotFoundException exception) { 78 exception.printStackTrace(); 79 } // if the format of the object name is wrong 82 catch ( MalformedObjectNameException exception ) { 83 exception.printStackTrace(); 84 } } // end PrinterEventHandler constructor // delegate out of paper event 89 private void handleOutOfPaperEvent() 90 { 91 eventTarget.outOfPaper(); 92 } // delegate low toner event 95 private void handleLowTonerEvent() 96 { 97 eventTarget.lowToner(); 98 } // delegate paper jam event 101 private void handlePaperJamEvent() 102 { 103 eventTarget.paperJam(); 104 } 105 } Delegate printer events

 2001 Prentice Hall, Inc. All rights reserved Management Application Management application for the case study –GUI for managing the printer ClientPrinterManagement ManagerSidePrinterEventListener PrinterManagementGUI

 2001 Prentice Hall, Inc. All rights reserved. Outline Class ClientPrinterManagement 1. Constructor 1.1 get RMI connector client 1 // Fig : ClientPrinterManagement.java 2 // This application establishes a connection to the MBeanServer 3 // and creates an MBean for PrinterSimulator. 4 5 // deitel package 6 package com.deitel.advjhtp1.jmx.Client; 7 8 // Java core packages 9 import java.awt.*; 10 import java.awt.event.*; // JMX core packages 13 import javax.management.*; // JDMX core packages 16 import com.sun.jdmk.comm.RmiConnectorClient; 17 import com.sun.jdmk.comm.RmiConnectorAddress; public class ClientPrinterManagement { private RmiConnectorClient rmiClient; // instantiate client connection 24 public ClientPrinterManagement() 25 { 26 // create connector client instance 27 rmiClient = new RmiConnectorClient(); // create address instance 30 RmiConnectorAddress rmiAddress = 31 new RmiConnectorAddress(); 32 Get RMI connector client

 2001 Prentice Hall, Inc. All rights reserved. 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 33 // specify port 34 rmiAddress.setPort( 5555 ); // establish connection 37 rmiClient.connect( rmiAddress ); } // end ClinetPrinterManagement constructor // return RmiConnectorClient reference 42 public RmiConnectorClient getClient() 43 { 44 return rmiClient; 45 } public static void main( String[] args ) 48 { 49 // instantiate client connection 50 ClientPrinterManagement clientManager = 51 new ClientPrinterManagement(); // get RMIConnectorClient handle 54 RmiConnectorClient client = clientManager.getClient(); // start GUI 57 PrinterManagementGUI printerManagementGUI = 58 new PrinterManagementGUI( client ); // display the output 61 printerManagementGUI.setSize( 62 new Dimension( 500, 500 ) ); 63 printerManagementGUI.setVisible( true ); } // end method main 66 } Set RMI client port Establish connection Invoke GUI

 2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterManagementGUI 1. Import packages 2. Inner class TextAppender 1 // Fig : PrinterManagementGUI.java 2 // This class defines the GUI for the 3 // printer management application. 4 5 // deitel package 6 package com.deitel.advjhtp1.jmx.Client; 7 8 // Java AWT core package 9 import java.awt.*; 10 import java.awt.event.*; // Java standard extensions 13 import javax.swing.*; // JMX core packages 16 import javax.management.*; // JDMX core packages 19 import com.sun.jdmk.comm.RmiConnectorClient; 20 import com.sun.jdmk.comm.RmiConnectorAddress; // Deitel packages 23 import com.deitel.advjhtp1.jmx.Printer.*; public class PrinterManagementGUI extends JFrame 26 implements PrinterEventListener { // TextAppender appends text to a JTextArea. This Runnable 29 // object should be executed only using SwingUtilities 30 // methods invokeLater or invokeAndWait as it modifies 31 // a live Swing component. 32 private class TextAppender implements Runnable { private String text; 35 private JTextArea textArea; 36 Inner class TextAppender

 2001 Prentice Hall, Inc. All rights reserved. Outline 3. Constructor 3.1 define status panel 37 // TextAppender constructor 38 public TextAppender( JTextArea area, String newText ) 39 { 40 text = newText; 41 textArea = area; 42 } // display new text in JTextArea 45 public void run() 46 { 47 // append new message 48 textArea.append( text ); // move caret to end of messageArea to ensure new 51 // message is visible on screen 52 textArea.setCaretPosition( 53 textArea.getText().length() ); 54 } } // end TextAppender inner class private ObjectName objectName; 59 private RmiConnectorClient client; 60 private JTextArea printerStatusTextArea = new JTextArea(); 61 private JTextArea printerEventTextArea = new JTextArea(); public PrinterManagementGUI( RmiConnectorClient rmiClient ) 64 { 65 super( "JMX Printer Management Example" ); Container container = getContentPane(); // status panel 70 JPanel printerStatusPanel = new JPanel(); 71 printerStatusPanel.setPreferredSize( 72 new Dimension( 512, 200 ) ); Define status panel

 2001 Prentice Hall, Inc. All rights reserved. Outline 3.2 define buttons panel define actions for the buttons 73 JScrollPane statusScrollPane = new JScrollPane(); 74 statusScrollPane.setAutoscrolls( true ); 75 statusScrollPane.setPreferredSize( 76 new Dimension( 400, 150 ) ); 77 statusScrollPane.getViewport().add( 78 printerStatusTextArea, null ); 79 printerStatusPanel.add( statusScrollPane, null ); // buttons panel 82 JPanel buttonPanel = new JPanel(); 83 buttonPanel.setPreferredSize( 84 new Dimension( 512, 200 ) ); // define action for Check Status button 87 JButton checkStatusButton = 88 new JButton( "Check Status" ); 89 checkStatusButton.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent event ) { 94 checkStatusButtonAction( event ); 95 } 96 } 97 ); // define action for Add Paper button 100 JButton addPaperButton = new JButton( "Add Paper" ); 101 addPaperButton.addActionListener( 102 new ActionListener() { public void actionPerformed(ActionEvent event) { 105 addPaperButtonAction( event ); 106 } 107 } 108 ); 109 Define buttons panel Define actions for the buttons

 2001 Prentice Hall, Inc. All rights reserved. Outline 3.3 define events panel 110 // define action for Cancel Pending Print Jobs button 111 JButton cancelPendingPrintJobsButton = new JButton( 112 "Cancel Pending Print Jobs" ); 113 cancelPendingPrintJobsButton.addActionListener( 114 new ActionListener() { public void actionPerformed( ActionEvent event ) { 117 cancelPendingPrintJobsButtonAction( event ); 118 } 119 } 120 ); // add three buttons to the panel 123 buttonPanel.add( checkStatusButton, null ); 124 buttonPanel.add( addPaperButton, null ); 125 buttonPanel.add( cancelPendingPrintJobsButton, null ); // events panel 128 JPanel printerEventPanel = new JPanel(); 129 printerEventPanel.setPreferredSize( 130 new Dimension( 512, 200) ); 131 JScrollPane eventsScrollPane = new JScrollPane(); 132 eventsScrollPane.setAutoscrolls( true ); 133 eventsScrollPane.setPreferredSize( 134 new Dimension( 400, 150 ) ); 135 eventsScrollPane.getViewport().add( 136 printerEventTextArea, null ); 137 printerEventPanel.add( eventsScrollPane, null ); // initialize the text 140 printerStatusTextArea.setText( "Printer Status: ---\n" ); 141 printerEventTextArea.setText( "Events: --- \n" ); // put all the panels together 144 container.add( printerStatusPanel, BorderLayout.NORTH ); 145 container.add( printerEventPanel, BorderLayout.SOUTH ); 146 container.add( buttonPanel, BorderLayout.CENTER ); Define actions for the buttons Define events panel

 2001 Prentice Hall, Inc. All rights reserved. Outline 3.4 start printer simulator 3.5 get PrinterEventHandler // set RmiConnectorClient reference 149 client = rmiClient; // invoke method startPrinting of the 152 // PrinterSimulator MBean 153 try { 154 String name = client.getDefaultDomain() ":type=" + "Printer"; 156 objectName = new ObjectName( name ); 157 client.invoke( objectName, "startPrinting", 158 new Object[ 0 ], new String[ 0 ] ); 159 } // invalid object name 162 catch ( MalformedObjectNameException exception ) { 163 exception.printStackTrace(); 164 } // if cannot invoke the method 167 catch ( ReflectionException exception) { 168 exception.printStackTrace(); 169 } // if invoked method throws exception 172 catch ( MBeanException exception ) { 173 exception.printStackTrace(); 174 } // if MBean is not registered with MBean server 177 catch ( InstanceNotFoundException exception ) { 178 exception.printStackTrace(); 179 } // instantiate PrinterEventNotifier 182 PrinterEventHandler printerEventHandler = 183 new PrinterEventHandler( client, this ); Start printing via MBean Get PrinterEventHandler

 2001 Prentice Hall, Inc. All rights reserved. Outline 3.6 define actions when close window // unregister MBean when close the window 186 addWindowListener( 187 new WindowAdapter() { 188 public void windowClosing( WindowEvent event ) 189 { 190 // unregister MBean 191 try { // unregister the PrinterSimulator MBean 194 client.unregisterMBean( objectName ); // unregister the PrinterEventBroadcaster 197 // MBean 198 String name = client.getDefaultDomain() ":type=" + "PrinterEventBroadcaster"; 200 objectName = new ObjectName( name ); 201 client.unregisterMBean( objectName ); 202 } // if invalid object name 205 catch ( MalformedObjectNameException exception) { 206 exception.printStackTrace(); 207 } // if exception is caught from method preDeregister 210 catch ( MBeanRegistrationException exception ) { 211 exception.printStackTrace(); 212 } // if MBean is not registered with MBean server 215 catch ( InstanceNotFoundException exception ) { 216 exception.printStackTrace(); 217 } 218 Unregister Mbeans when close window

 2001 Prentice Hall, Inc. All rights reserved. Outline 4 display events in events panel 219 // terminate the program 220 System.exit( 0 ); } // end method windowClosing } // end WindowAdapter constructor ); // end addWindowListener } // end PrinterManagementGUI constructor // out of paper events 231 public void outOfPaper() 232 { 233 SwingUtilities.invokeLater( 234 new TextAppender( printerEventTextArea, 235 "\nEVENT: Out of Paper!\n" ) ); 236 } // toner low events 239 public void lowToner() 240 { 241 SwingUtilities.invokeLater( 242 new TextAppender( printerEventTextArea, 243 "\nEVENT: Toner Low!\n" ) ); 244 } // paper jam events 247 public void paperJam() 248 { 249 SwingUtilities.invokeLater( 250 new TextAppender( printerEventTextArea, 251 "\nEVENT: Paper Jam!\n" ) ); 252 } Display events

 2001 Prentice Hall, Inc. All rights reserved. Outline 5. Add paper to printer 6. Cancel pending print jobs // add paper to the paper tray 255 public void addPaperButtonAction( ActionEvent event ) 256 { 257 try { 258 client.invoke( objectName, "replenishPaperTray", 259 new Object[ 0 ], new String[ 0 ] ); 260 } // if cannot invoke the method 263 catch ( ReflectionException exception) 264 { 265 exception.printStackTrace(); 266 } // if invoked method throws exception 269 catch ( MBeanException exception ) { 270 exception.printStackTrace(); 271 } // if MBean is not registered with MBean server 274 catch ( InstanceNotFoundException exception ) { 275 exception.printStackTrace(); 276 } } // end method addPaperButtonAction // cancel pending print jobs 281 public void cancelPendingPrintJobsButtonAction( 282 ActionEvent event ) 283 { 284 try { 285 client.invoke( objectName, "cancelPendingPrintJobs", 286 new Object[ 0 ], new String[ 0 ] ); 287 } Add paper to paper try when click Add Paper button Cancel pending print jobs when click Cancel Pending Print Jobs button

 2001 Prentice Hall, Inc. All rights reserved. Outline 7. Check printer’s status 7.1 get printer’s status // if cannot invoke the method 290 catch ( ReflectionException exception) 291 { 292 exception.printStackTrace(); 293 } // if invoked method throws exception 296 catch ( MBeanException exception ) { 297 exception.printStackTrace(); 298 } // if MBean is not registered with MBean server 301 catch ( InstanceNotFoundException exception ) { 302 exception.printStackTrace(); 303 } } // end method cancelPendingPrintJobsButtonAction public void checkStatusButtonAction( ActionEvent event ) 308 { 309 Object onlineResponse = null; 310 Object paperJamResponse = null; 311 Object printingResponse = null; 312 Object paperTrayResponse = null; 313 Object pendingPrintJobsResponse = null; // manage printer remotely 316 try { // check if the printer is on line 319 onlineResponse = client.invoke( objectName, 320 "isOnline", new Object[ 0 ], new String[ 0 ] ); 321 Check printer’s status when click Check Status button

 2001 Prentice Hall, Inc. All rights reserved. Outline 7.2 prepare output 322 // check if the printer is paper jammed 323 paperJamResponse = client.invoke( objectName, 324 "isPaperJam", new Object[ 0 ], new String[ 0 ] ); // check if the printing is pringint 327 printingResponse = client.invoke( objectName, 328 "isPrinting", new Object[ 0 ], new String[ 0 ] ); // get the paper tray 331 paperTrayResponse = client.invoke( objectName, 332 "getPaperTray", new Object[ 0 ], new String[ 0 ] ); // get pending print jobs 335 pendingPrintJobsResponse = client.invoke( objectName, 336 "getPendingPrintJobs", new Object[ 0 ], 337 new String[ 0 ] ); 338 } // if cannot invoke the method 341 catch ( ReflectionException exception ) { 342 exception.printStackTrace(); 343 } // if invoked method throws exception 346 catch ( MBeanException exception ) { 347 exception.printStackTrace(); 348 } // if MBean is not registered with MBean server 351 catch ( InstanceNotFoundException exception ) { 352 exception.printStackTrace(); 353 } // status for the online condition 356 boolean isOnline = 357 ( ( Boolean ) onlineResponse ).booleanValue(); Check printer’s status by calling methods on Printer MBean

 2001 Prentice Hall, Inc. All rights reserved. Outline 7.2 prepare output // display status 360 if ( isOnline ) { 361 SwingUtilities.invokeLater( new TextAppender( 362 printerStatusTextArea, 363 "\nPrinter is ONLINE.\n" ) ); 364 } 365 else { 366 SwingUtilities.invokeLater( new TextAppender( 367 printerStatusTextArea, 368 "\nPrinter is OFFLINE.\n" ) ); 369 } // status for the paper jam condition 372 boolean isPaperJam = 373 ( ( Boolean ) paperJamResponse ).booleanValue(); // display status 376 if ( isPaperJam ) { 377 SwingUtilities.invokeLater( new TextAppender( 378 printerStatusTextArea, 379 "Paper jammed.\n" ) ); 380 } 381 else { 382 SwingUtilities.invokeLater( new TextAppender( 383 printerStatusTextArea, 384 "No Paper Jam.\n" ) ); 385 } // status for the printing condition 388 boolean isPrinting = 389 ( ( Boolean )printingResponse ).booleanValue(); 390 Append printer status to output area

 2001 Prentice Hall, Inc. All rights reserved. Outline 7.2 prepare output 391 // display status 392 if ( isPrinting ) { 393 SwingUtilities.invokeLater( new TextAppender( 394 printerStatusTextArea, 395 "Printer is currently printing.\n" ) ); 396 } 397 else { 398 SwingUtilities.invokeLater( new TextAppender( 399 printerStatusTextArea, 400 "Printer is not printing.\n" ) ); 401 } // status for paper tray condition 404 int paperRemaining = 405 ( ( Integer )paperTrayResponse ).intValue(); // display status 408 SwingUtilities.invokeLater( new TextAppender( 409 printerStatusTextArea, 410 "Printer paper tray has " + paperRemaining " pages remaining.\n" ) ); // status for pending print jobs 414 Object[] pendingPrintJobs = 415 ( Object[] ) pendingPrintJobsResponse; 416 int pendingPrintJobsNumber = pendingPrintJobs.length; // display status 419 SwingUtilities.invokeLater( new TextAppender( 420 printerStatusTextArea, 421 "Number of pending print jobs: " pendingPrintJobsNumber + "\n" ) ); } // end method checkStatusButtonAction 426 } Append printer status to output area

 2001 Prentice Hall, Inc. All rights reserved 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 Out-of-paper event happened Status after 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