Download presentation
Presentation is loading. Please wait.
Published bySolomon Atkins Modified over 9 years ago
1
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 Services 25.5 Dynamic Services 25.5.1 Dynamic-Service Implementation 25.6 Static Services 25.6.1 Locating the Static Services with Class ServiceFinder 25.6.2 Event Service 25.6.3 Log Service 25.6.4 Scheduling Service 25.7 Dynamic Service Deployment 25.7.1 Dynamic-Service Usage 25.8 Management Policies 25.8.1 Policy–Management Deployment 25.9 Putting It All Together 25.10 Internet and World Wide Web Resources
2
2001 Prentice Hall, Inc. All rights reserved. 25.1 Introduction Manage distributed resources, networks, devices –Complex –Expensive Management solution –Automated –Centralized –Standardized –Open and interoperable –Platform independent –Fast to develop and easy to deploy –Highly available
3
2001 Prentice Hall, Inc. All rights reserved. 25.1 Introduction Jiro technology –Implementation of FMA –Supports a three-tier architecture of management solutions Clients Management services resources –Supports existing industry standards –Relation to Jini and RMI
4
2001 Prentice Hall, Inc. All rights reserved. 25.2 Installation Download –Jiro Runtime Environment –Jiro Technology Software Development Kit (SDK) Install –Location of Java v 1.3.0 –Management domain name Uniquely identified on the local network
5
2001 Prentice Hall, Inc. All rights reserved. 25.3 Starting Jiro Igniter –Start –Stop –Clean
6
2001 Prentice Hall, Inc. All rights reserved. 25.3 Starting Jiro
7
2001 Prentice Hall, Inc. All rights reserved. 25.4 Dynamic vs. Static Services Dynamic services –Customized services Static services –Transaction service –Controller –Event service –Scheduling service –Log service Difference between dynamic and static services
8
2001 Prentice Hall, Inc. All rights reserved. 25.5 Dynamic Services Jiro station –Host dynamic services –Allow clients access dynamic service Management Façade Façade design pattern Make a dynamic service available –Implement the dynamic service –Deploy the dynamic service
9
2001 Prentice Hall, Inc. All rights reserved. 25.5.1 Dynamic-Service Implementation Define public interface –PrinterManagement Service implementation –PrinterManagementImpl Point object implementing method getLookupEntries Helper class –PrinterEventListener
10
2001 Prentice Hall, Inc. All rights reserved. Outline Interface PrinterManagement 1. Management operations 1 // Fig: PrinterManagement.java 2 // This class defines the interface for the dynamic service. 3 package com.deitel.advjhtp1.jiro.DynamicService.service; 4 5 // Java core package 6 import java.rmi.*; 7 import java.util.*; 8 9 // Jini core package 10 import net.jini.core.event.*; 11 12 public interface PrinterManagement 13 extends RemoteEventListener { 14 15 public void addPaper( int amount ) 16 throws RemoteException; 17 18 public boolean isPrinting() throws RemoteException; 19 20 public boolean isPaperJam() throws RemoteException; 21 22 public int getPaperInTray() throws RemoteException; 23 24 public boolean isOnline() throws RemoteException; 25 26 public void cancelPendingPrintJobs() throws RemoteException; 27 28 public void terminateScheduledTasks() throws RemoteException; 29 30 public void addToner() throws RemoteException; 31 32 public String[] getPendingPrintJobs() throws RemoteException; 33 } Management operations
11
2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterManagementImpl 1. Import packages 1 // PrinterManagementImpl.java 2 // This class schedules turn-on and turn-off printer 3 // periodically and issues a log message to LogService 4 // when error events happen. 5 package com.deitel.advjhtp1.jiro.DynamicService.service; 6 7 // Java core packages 8 import java.io.Serializable; 9 import java.rmi.*; 10 import java.util.*; 11 12 // Java standard extensions 13 import javax.swing.*; 14 15 // Jini core packages 16 import net.jini.core.event.*; 17 import net.jini.core.entry.*; 18 import net.jini.core.lease.*; 19 20 // Jini extension packages 21 import net.jini.lease.LeaseRenewalManager; 22 import net.jini.lookup.entry.*; 23 24 // Jiro packages 25 import javax.fma.services.ServiceFinder; 26 import javax.fma.services.event.EventService; 27 import javax.fma.services.log.LogMessage; 28 import javax.fma.services.log.LogService; 29 import javax.fma.services.scheduling.SchedulingService; 30 import javax.fma.services.scheduling.SchedulingService.*; 31 import javax.fma.util.*; 32 33 // Deitel packages 34 import com.deitel.advjhtp1.jiro.DynamicService.printer.*; 35
12
2001 Prentice Hall, Inc. All rights reserved. Outline 2. Declarations 3. Constructor 3.1 start printer 3.2 get static services 3.3 create a listener 36 public class PrinterManagementImpl 37 implements PrinterManagement { 38 39 private Printer printer; 40 private LogService logService = null; 41 private Lease observerLease; 42 private LeaseRenewalManager leaseRenewalManager; 43 private Ticket turnOffPrinter; 44 private Ticket turnOnPrinter; 45 46 // default constructor 47 public PrinterManagementImpl() 48 { 49 System.out.println( "Dynamic service started.\n" ); 50 51 // start a printer 52 printer = new Printer() ; 53 Thread printerThread = new Thread( printer ) ; 54 printerThread.start(); 55 56 // subscribe to printer events 57 try { 58 59 // get the event service 60 EventService eventService = 61 ServiceFinder.getEventService(); 62 63 // get the log service 64 logService = ServiceFinder.getLogService(); 65 66 // get a listener 67 PrinterEventListener listener = 68 new PrinterEventListener( this ); 69 Start printerGet static servicesCreate a listener
13
2001 Prentice Hall, Inc. All rights reserved. Outline 3.4 subscribe to printer event 3.5 schedule turn-off activity 70 // subscribe as an observing listener to event with 71 // topic ".Printer.Error" 72 observerLease = eventService.subscribeObserver( 73 ".Printer.Error", listener, null, 10 * 60 * 1000 ); 74 75 // renew observer listener's lease 76 leaseRenewalManager = new LeaseRenewalManager(); 77 leaseRenewalManager.renewUntil( 78 observerLease, Lease.FOREVER, null ); 79 80 // get the scheduling service 81 SchedulingService schedulingService = 82 ServiceFinder.getSchedulingService(); 83 84 // define the schedule for turn-off printer task 85 // printer is turned off at 8:00PM every friday 86 GregorianCalendar calendar = new GregorianCalendar(); 87 calendar.set( 2001, 7, 27 ); 88 Date startDate = calendar.getTime(); 89 calendar.set( 2003, 7, 27 ); 90 Date endDate = calendar.getTime(); 91 int[] monthsOff = { Calendar.JANUARY, 92 Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, 93 Calendar.MAY, Calendar.JUNE, Calendar.JULY, 94 Calendar.AUGUST, Calendar.SEPTEMBER, 95 Calendar.OCTOBER, Calendar.NOVEMBER, 96 Calendar.DECEMBER }; 97 int[] daysOfWeekOff = { Calendar.FRIDAY }; 98 int[] hoursOff = { 20 }; 99 int[] minutesOff = { 0 }; 100 Subscribe to event with topic “.Printer.Error” Get scheduling service Turn off printer at 8:00pm every Friday between Aug 27, 2001 and Aug 27, 2003
14
2001 Prentice Hall, Inc. All rights reserved. Outline 3.6 schedule turn-on activity 101 // create the schedule for turn-off printer task 102 Schedule turnOffSchedule = 103 schedulingService.newRepeatedDateSchedule( 104 startDate, endDate, monthsOff, null, 105 daysOfWeekOff, hoursOff, minutesOff, 106 calendar.getTimeZone() ); 107 108 // create the message description 109 LocalizableMessage turnOffMessage = 110 new LocalizableMessage( PrinterManagementImpl.class, 111 "TurnOffPrinter", null, null ); 112 113 // define the handback object of the 114 // turn-off printer task 115 MarshalledObject handbackOff = new MarshalledObject( 116 new String( "turn-off" ) ); 117 118 // schedule task and get the Ticket for 119 // the scheduled task 120 turnOffPrinter = schedulingService.scheduleTask( 121 listener, turnOffMessage, turnOffSchedule, 122 SchedulingService.NONE, handbackOff ); 123 124 // define the schedule for turn-on printer task 125 // printer is turned on at 7:00AM every Monday 126 calendar = new GregorianCalendar(); 127 calendar.set( 2001, 7, 27 ); 128 startDate = calendar.getTime(); 129 calendar.set( 2003, 7, 27 ); 130 endDate = calendar.getTime(); Generate the turn- off Schedule handback objectTurn on printer at 7:00pm every Monday between Aug 27, 2001 and Aug 27, 2003 Obtain ticket for turn-off schedule
15
2001 Prentice Hall, Inc. All rights reserved. Outline 131 int[] monthsOn = { Calendar.JANUARY, 132 Calendar.FEBRUARY, Calendar.MARCH, Calendar.APRIL, 133 Calendar.MAY, Calendar.JUNE, Calendar.JULY, 134 Calendar.AUGUST, Calendar.SEPTEMBER, 135 Calendar.OCTOBER, Calendar.NOVEMBER, 136 Calendar.DECEMBER }; 137 int[] daysOfWeekOn = { Calendar.MONDAY }; 138 int[] hoursOn = { 7 }; 139 int[] minutesOn = { 0 }; 140 141 // create the schedule for turn-on printer task 142 Schedule turnOnSchedule = 143 schedulingService.newRepeatedDateSchedule( 144 startDate, endDate, monthsOn, null, 145 daysOfWeekOn, hoursOn, minutesOn, 146 calendar.getTimeZone() ); 147 148 // create the message description 149 LocalizableMessage turnOnMessage = 150 new LocalizableMessage( PrinterManagementImpl.class, 151 "TurnOnPrinter", null, null ); 152 153 // define the handback object of the 154 // turn-on printer task 155 MarshalledObject handbackOn = new MarshalledObject( 156 new String( "turn-on" ) ); 157 158 // schedule task and get the Ticket for 159 // the scheduled task 160 turnOnPrinter = schedulingService.scheduleTask( 161 listener, turnOnMessage, turnOnSchedule, 162 SchedulingService.NONE, handbackOn ); 163 164 } // end try 165 Generate the turn- on Schedule handback objectObtain ticket for turn-on schedule
16
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Cancel scheduled task 166 // handle exception schedulling task 167 catch ( Exception exception ) { 168 System.out.println( "PrinterManagementImpl: " + 169 "Exception occurred when scheduling tasks." ); 170 System.out.println( "Please read debug file...\n" ); 171 Debug.debugException( "schedulling task", exception ); 172 } 173 174 } // end PrinterManagementImpl constructor 175 176 // cancel scheduled tasks 177 public void terminateScheduledTasks() 178 { 179 // cancel turn-on and turn-off printer tasks 180 try { 181 turnOffPrinter.cancel(); 182 turnOnPrinter.cancel(); 183 } 184 185 // handle exception canceling scheduled task 186 catch ( Exception exception ) { 187 System.out.println( "PrinterManagementImpl: " + 188 "Exception occurred when canceling tasks." ); 189 System.out.println( "Please read debug file...\n" ); 190 Debug.debugException( 191 "cancel scheduled task", exception ); 192 } 193 194 } // end cancel scheduled task 195 Cancel ticket
17
2001 Prentice Hall, Inc. All rights reserved. Outline 5. Management operations 196 // add paper to printer 197 public void addPaper( int amount ) 198 { 199 System.out.println( 200 "PrinterManagementImpl: Adding paper...\n" ); 201 printer.replenishPaperTray( amount ); 202 } 203 204 // is printer printing? 205 public boolean isPrinting() 206 { 207 return printer.isPrinting(); 208 } 209 210 // is printer jammed? 211 public boolean isPaperJam() 212 { 213 return printer.isPaperJam(); 214 } 215 216 // get printer's pages count 217 public int getPaperInTray() 218 { 219 return printer.getPaperInTray(); 220 } 221 222 // get pending jobs 223 public String[] getPendingPrintJobs() 224 { 225 return printer.getPendingPrintJobs(); 226 } 227
18
2001 Prentice Hall, Inc. All rights reserved. Outline 5. Management operations 6. Receive event and scheduling notification 228 // is printer online? 229 public boolean isOnline() 230 { 231 return printer.isOnline(); 232 } 233 234 // cancel pending printing jobs 235 public void cancelPendingPrintJobs() 236 { 237 System.out.println( "PrinterManagementImpl: " 238 + "Canceling pending print jobs... \n" ); 239 printer.cancelPendingPrintJobs(); 240 } 241 242 // receive notifications 243 public void notify( RemoteEvent remoteEvent ) 244 throws UnknownEventException, RemoteException 245 { 246 String subString = 247 "com.deitel.advjhtp1.jiro.DynamicService.printer"; 248 String source = ( String ) remoteEvent.getSource(); 249 source = source.substring( 0, subString.length() ); 250 251 // printer event 252 if ( source.equals( subString ) ) 253 eventHandler( remoteEvent ); 254 255 else // scheduled task 256 performTask( remoteEvent ); 257 } 258 Identify event source and take corresponding action
19
2001 Prentice Hall, Inc. All rights reserved. Outline 7. Perform scheduled task 259 // add toner to printer 260 public void addToner() 261 { 262 System.out.println( 263 "PrinterManagementImpl: Adding toner...\n" ); 264 printer.addToner(); 265 } 266 267 // perform task when scheduled time arrives 268 private void performTask( RemoteEvent remoteEvent ) 269 { 270 // perform task 271 try { 272 273 // get task type 274 String type = 275 ( String ) remoteEvent.getRegistrationObject().get(); 276 277 // turn-off printer 278 if ( type.equals( "turn-off" ) ) 279 printer.setOffline(); 280 281 // turn-on printer 282 else if ( type.equals( "turn-on" ) ) 283 printer.setOnline(); 284 } 285 286 // handle exception performing scheduled task 287 catch (Exception exception) { 288 System.out.println( "PrinterManagementImpl: " + 289 "Exception occurred when performing tasks." ); 290 System.out.println( "Please read debug file...\n" ); 291 Debug.debugException( 292 "perform scheduled task", exception ); 293 } 294 295 } // end method performTask Identify turn-on or turn-off activity based on handback object
20
2001 Prentice Hall, Inc. All rights reserved. Outline 8. Handle printer event 296 297 // handle event 298 private synchronized void eventHandler ( 299 RemoteEvent remoteEvent ) 300 { 301 String source = ( String ) remoteEvent.getSource(); 302 303 // generate the log message 304 Serializable params[] = new Serializable[ 2 ]; 305 params[ 0 ] = source; 306 params[ 1 ] = new Date(); 307 308 // define localizable message 309 LocalizableMessage localizableMessage = 310 new LocalizableMessage( PrinterManagementImpl.class, 311 "Event", params, Locale.US ); 312 313 // define log message 314 LogMessage logMessage = new LogMessage( 315 localizableMessage, LogMessage.TRACE + ".printer." 316 + source, null ); 317 318 // post the log message 319 try { 320 logService.log( logMessage ); 321 } 322 323 // handle exception posting log message 324 catch ( Exception exception ) { 325 System.out.println( "PrinterManagementImpl: " + 326 "Exception occurred when posting log message." ); 327 System.out.println( "Please read debug file...\n" ); 328 Debug.debugException( "log service", exception ); 329 } 330 331 } // end eventHandler Log printer events Define log message
21
2001 Prentice Hall, Inc. All rights reserved. Outline 9. Declare dynamic service 332 333 // entry object 334 private Entry[] getLookupEntries() 335 { 336 return ( new Entry[] { 337 new ServiceInfo( "PrinterManagementImpl", 338 "Deitel Association, Inc.", 339 "Deitel Association, Inc", 340 "1.0", "Model 0", "0.0.0.1" ) 341 } 342 ); 343 } 344 } Implement getLookupEntries to declare this class as dynamic service Entry object for the dynamic service, client use this Entry to locate dynamic service
22
2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterEventListener 1. Constructor 2. Forward notification 1 // PrinterEventListener.java 2 // This class defines the listener that listens for events 3 // issued by a printer. 4 package com.deitel.advjhtp1.jiro.DynamicService.service; 5 6 // Java core packages 7 import java.rmi.*; 8 import java.rmi.server.UnicastRemoteObject; 9 10 // Jini core packages 11 import net.jini.core.event.*; 12 13 public class PrinterEventListener 14 implements RemoteEventListener { 15 16 private RemoteEventListener eventListener; 17 18 // PrinterEventListener constructor 19 public PrinterEventListener( RemoteEventListener listener ) 20 { 21 eventListener = listener; 22 23 // export the stub object 24 try { 25 UnicastRemoteObject.exportObject( this ); 26 } 27 28 // handle exception exporting stub 29 catch ( RemoteException remoteException ) { 30 remoteException.printStackTrace(); 31 } 32 33 } // end PrinterEventListener constructor 34 35 // receive the notification 36 public void notify( RemoteEvent remoteEvent ) 37 throws UnknownEventException, RemoteException 38 { 39 // forward notification 40 eventListener.notify( remoteEvent ); 41 } 42 } Export stubForward notification
23
2001 Prentice Hall, Inc. All rights reserved. 25.6 Static Services Static Services –Event service –Log service –Scheduling service –Transaction service –Controller service
24
2001 Prentice Hall, Inc. All rights reserved. 25.6.1 Locating the Static Services with Class ServiceFinder Class ServiceFinder –Provides a convenient way to locate static services –Ten methods –Two for each static service
25
2001 Prentice Hall, Inc. All rights reserved. 25.6.2 Event Service Three types of elements –Event publisher –Event subscriber Observer listener Responsible listener –Chain-of-Responsibility design pattern –Event Event topics
26
2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterErrorEvent 1. Constructor 2. Clone event 1 // PrinterErrorEvent.java 2 // This class defines the events issued by a printer. 3 package com.deitel.advjhtp1.jiro.DynamicService.printer; 4 5 // Jiro package 6 import javax.fma.services.event.Event; 7 8 public class PrinterErrorEvent 9 extends Event implements Cloneable { 10 11 // PrinterErrorEvent constructor 12 public PrinterErrorEvent( Object source, String topic ) 13 { 14 super ( source, topic ); 15 } 16 17 // clone event 18 public Object clone() 19 { 20 return new PrinterErrorEvent( source, getTopic() ); 21 } 22 } Implement Cloneable so that the event service can make multiple copies of the event object Clone event object
27
2001 Prentice Hall, Inc. All rights reserved. Outline Class Printer 1. Import packages 2. Declarations 1 // Printer.java 2 // This class simulates a printer device on a network. 3 // deitel package 4 package com.deitel.advjhtp1.jiro.DynamicService.printer; 5 6 // java core package 7 import java.util.Stack; 8 import java.rmi.*; 9 import java.io.*; 10 11 // Jiro packages 12 import javax.fma.services.ServiceFinder; 13 import javax.fma.services.event.EventService; 14 import javax.fma.util.*; 15 16 public class Printer implements Runnable { 17 18 private Stack printerStack = new Stack(); 19 private boolean isPrinting = false; 20 private boolean isPaperJam = false; 21 private boolean isOnline = true; 22 23 // 50 sheets of paper in tray 24 private int paperInTray = 50; 25 26 // 100% full of ink 27 private int tonerCartridge = 100; 28 29 private String currentPrintJob; 30 private boolean isAlive = true; 31 32 private EventService eventService; 33
28
2001 Prentice Hall, Inc. All rights reserved. Outline 3. Construtor 4. Simulate printer 34 // printer constructor 35 public Printer() 36 { 37 // get EventService at given management domain 38 try { 39 eventService = ServiceFinder.getEventService(); 40 } 41 42 // handle exception getting EventService 43 catch ( Exception exception ) { 44 Debug.debugException( 45 "getting EventService", exception ); 46 } 47 } 48 49 // stops execution of thread 50 public void stop() 51 { 52 isAlive = false; 53 } 54 55 // main life-cycle of the printer. 56 // prints one job from print job stack 57 // 1) if offline, it pauses and waits. 58 // 2) if online, handles one print job 59 public void run() 60 { 61 // main loop within thread 62 while ( isAlive ) { 63 Get event service using class ServiceFinder
29
2001 Prentice Hall, Inc. All rights reserved. Outline 4. simulate printer 64 // printer will be offline 65 if ( !isOnline ) { 66 67 synchronized ( this ) { 68 69 // waits for printer become online 70 try { 71 wait(); 72 } 73 74 // handle exception waiting 75 catch ( InterruptedException exception ) { 76 Debug.debugException( 77 "printer wait", exception ); 78 } 79 80 } // end synchronized 81 82 } // end if 83 84 // prints one job from print job stack 85 startPrintingProcess(); 86 87 } // end while 88 } 89 90 // start printing process 91 private synchronized void startPrintingProcess() 92 { 93 // warm up the printer, print top print job from print 94 // stack and adjust paper values and toner values 95 try { 96 97 // warm up printer for incoming batch of print jobs 98 Thread.sleep( 1000 * 2 );
30
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Simulate printer 99 100 if ( isOnline && ( paperInTray > 0 ) && 101 ( tonerCartridge > 10 ) && ( !isPaperJam ) ) { 102 103 // start the printing process 104 currentPrintJob = getNextPrintJob(); 105 isPrinting = true; 106 107 // 12 seconds to print a normal document 108 Thread.sleep( 1000 * 12 ); 109 110 // each print job uses 10 pages 111 updatePaperInTray( paperInTray - 10 ); 112 updateToner(); 113 updatePaperJam(); 114 isPrinting = false; 115 116 // make sure no referrences are left dangling 117 currentPrintJob = null; 118 119 } // end if 120 } 121 122 // handle exception starting printing process 123 catch( InterruptedException exception ) { 124 Debug.debugException( 125 "starting printing process", exception ); 126 } 127 128 } // end method startPrintingProcess 129 130 // returns current printed job 131 private String getCurrentPrintJob() 132 { 133 return currentPrintJob; 134 } Printing processUpdate printer status
31
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Simulate printer 135 136 // update amount of paper in paper tray 137 private synchronized void updatePaperInTray( int newValue ) 138 { 139 paperInTray = newValue; 140 141 // fire event if paper tray low 142 if ( paperInTray <= 0 ) { 143 System.out.println( "Printer: out of paper. " ); 144 fireEvent( "OutofPaper" ); 145 } 146 } 147 148 // is paper jammed? 149 public boolean isPaperJam() 150 { 151 return isPaperJam; 152 } 153 154 // is printer printing? 155 public boolean isPrinting() 156 { 157 return isPrinting; 158 } 159 160 // is printer online? 161 public boolean isOnline() 162 { 163 return isOnline; 164 } 165 166 // return number of pages in paper tray 167 public synchronized int getPaperInTray() 168 { 169 return paperInTray; 170 } Update paper count and if paper tray is low fire out-of-paper event
32
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Simulate printer 171 172 // update amount of toner available in toner cartridge 173 public synchronized void updateToner() 174 { 175 // after every print job, toner levels drop 1% 176 tonerCartridge = tonerCartridge - 1; 177 178 // fire event if toner is low 179 if ( tonerCartridge <= 10 ) { 180 System.out.println( "Printer: low toner. " ); 181 fireEvent( "LowToner" ); 182 } 183 } 184 185 // update paper jam 186 public synchronized void updatePaperJam() 187 { 188 if ( Math.random() > 0.9 ) { 189 isPaperJam = true; 190 System.out.println( "Printer: paper jam. " ); 191 fireEvent( "PaperJam" ); 192 } 193 } 194 195 // return amount of toner in toner cartridge 196 public synchronized int getToner() 197 { 198 return tonerCartridge; 199 } 200 Update toner level and if toner is low fire low-toner event Simulate paper jam and if paper jam fire paper-jam event
33
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Simulate printer 201 // replenishe amount of paper in paper tray to specified 202 // value 203 public void replenishPaperTray ( int paperStack ) 204 { 205 System.out.println( "Printer: adding " + paperStack 206 + " pages to printer... \n" ); 207 updatePaperInTray ( paperInTray + paperStack ) ; 208 } 209 210 // generates a random number of print jobs with varying IDs 211 private synchronized void populatePrintStack() 212 { 213 int numOfJobs = ( int ) ( Math.random ( ) * 10 ) + 1; 214 215 // generate print jobs 216 for ( int i = 0; i < numOfJobs ; i++ ) { 217 218 synchronized ( printerStack ) { 219 printerStack.add ( "PRINT_JOB_ID #" + i ); 220 } 221 } 222 } 223 224 // add toner 225 public synchronized void addToner() 226 { 227 System.out.println( "Printer: adding toner... \n" ); 228 tonerCartridge = 100; 229 } 230 231 // cancel pending print jobs 232 public synchronized void cancelPendingPrintJobs() 233 { 234 synchronized ( printerStack ) { 235 printerStack.clear(); 236 } 237 } Add paper to paper tray Refill toner
34
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Simulate printer 238 239 // return next print job in stack, populating the stack 240 // if it is empty 241 private synchronized String getNextPrintJob() 242 { 243 if ( printerStack.isEmpty() ) { 244 populatePrintStack ( ); 245 246 // simulates absence of print jobs 247 try { 248 Thread.sleep ( 249 ( int ) ( Math.random() * 1000 * 10 ) ); 250 } 251 252 // handle exception thread sleep 253 catch ( InterruptedException exception ) { 254 Debug.debugException( 255 "getting next print job", exception ); 256 } 257 } 258 259 // Remove topmost queued resource. 260 String nextJob; 261 262 synchronized ( printerStack ) { 263 nextJob = ( String ) printerStack.pop(); 264 } 265 266 return nextJob; 267 268 } // end method getNextPrintJob 269
35
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Simulate printer 270 // return all jobs yet to be printed 271 public synchronized String[] getPendingPrintJobs() 272 { 273 String[] pendingJobs; 274 275 // create array of pending print jobs 276 synchronized ( printerStack ) { 277 Object[] temp = printerStack.toArray() ; 278 pendingJobs = new String[ temp.length ] ; 279 280 for ( int i = 0; i < pendingJobs.length ; i++ ) { 281 pendingJobs [ i ] = ( String ) temp[ i ]; 282 } 283 } 284 285 return pendingJobs; 286 } 287 288 // set printer status to online 289 public void setOnline() 290 { 291 System.out.println( "Printer: setting online... \n" ); 292 isOnline = true; 293 294 // notify all waiting states 295 synchronized ( this ) { 296 notifyAll() ; 297 } 298 } 299 300 // set printer status to offline 301 public void setOffline() 302 { 303 System.out.println( "Printer: setting offline... \n" ); 304 isOnline = false; 305 } Get pending print jobs
36
2001 Prentice Hall, Inc. All rights reserved. Outline 5. Fire printer events 306 307 // fire event 308 private void fireEvent( String error ) 309 { 310 // post event to EventService 311 try { 312 313 // define event 314 PrinterErrorEvent event = new PrinterErrorEvent( 315 "com.deitel.advjhtp1.jiro.DynamicService.printer." 316 + "ErrorMessage=" + error, 317 ".Printer.Error." + error ); 318 319 // post event 320 eventService.post( event ); 321 } 322 323 // handle exception posting event 324 catch ( Exception exception ) { 325 Debug.debugException( "posting event", exception ); 326 } 327 328 } // end method fireEvent 329 } Define event source and topic- “.Printer.Error.”+error type Post an event to EventService
37
2001 Prentice Hall, Inc. All rights reserved. 25.6.3 Log Service Log Service –internationalized Post a log message –Localizable message –Message categories AUDIT DEBUG WARNING INFO ERROR TRACE Retrieve log messages
38
2001 Prentice Hall, Inc. All rights reserved. 25.6.3 Log Service Resource file –Key = value pair(s) –Location View log message –viewlog –domain jirodomain
39
2001 Prentice Hall, Inc. All rights reserved. Outline Resouce file for PrinterManagementImpl 1 Event = {0} event occurred on {1}. 2 TurnOffPrinter = Turn off the printer. 3 TurnOnPrinter = Turn on the printer. Fig. 25.9PrinterManagementImpl.properties file Resource file
40
2001 Prentice Hall, Inc. All rights reserved. 25.6.4 Scheduling Service Schedule future tasks Method newRepeatedDateSchedule –Schedule repeated tasks Later performance policy A listener
41
2001 Prentice Hall, Inc. All rights reserved. 25.7 Dynamic Service Deployment Deploy dynamic service –Generate service proxy Tools: jiroc and jirocw –Create deployment JAR files Interface JAR Implementation JAR Download JAR –Pack JAR files Tools: jarpackw –Deploy dynamic service Tools: jardeploy
42
2001 Prentice Hall, Inc. All rights reserved. Outline
43
2001 Prentice Hall, Inc. All rights reserved. 25.7.1 Dynamic Service Usage To use a dynamic service –Instantiate the dynamic service (first time use) PrinterManagementStarter –Use lookup service to find the dynamic service DynamicServiceFinder –Printer management console PrinterClientGUI
44
2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterManagementStarter 1. Constructor 1.1 set security manager 1.2 obtain station address 1 // Fig: PrinterManagementStarter.java 2 // This application demonstrates how to obtain the proxies of 3 // a dynamic service. 4 package com.deitel.advjhtp1.jiro.DynamicService.client; 5 6 // Java core package 7 import java.rmi.*; 8 9 // Jiro packages 10 import javax.fma.common.*; 11 12 // Deitel packages 13 import com.deitel.advjhtp1.jiro.DynamicService.service.*; 14 15 public class PrinterManagementStarter { 16 17 // PrinterManagementStarter constructor 18 public PrinterManagementStarter( String domain ) { 19 20 PrinterManagement managementProxy; 21 22 // set security manager 23 if ( System.getSecurityManager() == null ) 24 System.setSecurityManager( new RMISecurityManager() ); 25 26 // obtain station address 27 StationAddress stationAddress = 28 new StationAddress( domain, 29 null, null, null, null, null, null, null ); 30 Set security managerObtain station address
45
2001 Prentice Hall, Inc. All rights reserved. Outline 1.3 instantiate dynamic service 2. main 31 // get the proxies of dynamic services 32 // and start the services 33 try { 34 managementProxy = 35 new PrinterManagementImplProxy( stationAddress ); 36 } 37 38 // handle exception getting proxies and starting policies 39 catch ( RemoteException exception ) { 40 exception.printStackTrace(); 41 } 42 43 } // end PrinterManagementStarter constructor 44 45 // method main 46 public static void main( String args[] ) 47 { 48 String domain = ""; 49 50 // get the domain name 51 if ( args.length != 1 ) { 52 System.out.println( 53 "Usage: PrinterManagementStarter Domain" ); 54 System.exit( 1 ); 55 } 56 else 57 domain = args[ 0 ]; 58 59 PrinterManagementStarter printerManagementStarter = 60 new PrinterManagementStarter( domain ); 61 62 } // end main method 63 } Instantiate dynamic service
46
2001 Prentice Hall, Inc. All rights reserved. Outline Class DynamicServiceFinder 1. Import packages 2. Declaration 3. Constructor 3.1 set security manager 1 // DynamicServiceFinder.java 2 // This class discovers lookup services and 3 // gets dynamic service proxy. 4 package com.deitel.advjhtp1.jiro.DynamicService.common; 5 6 // Java core packages 7 import java.rmi.*; 8 import java.io.*; 9 10 // Jini core packages 11 import net.jini.core.entry.Entry; 12 import net.jini.core.lookup.*; 13 14 // Jini extension packages 15 import net.jini.discovery.*; 16 import net.jini.lookup.entry.ServiceInfo; 17 18 // Jiro packages 19 import javax.fma.util.*; 20 21 public class DynamicServiceFinder 22 implements DiscoveryListener { 23 24 private int servicesFound = 0; 25 private ServiceRegistrar[] registrars; 26 private Entry[] entries; 27 28 // DynamicServiceFinder constructor 29 public DynamicServiceFinder ( 30 String domain, Entry[] serviceEntries ) 31 { 32 System.setSecurityManager( new RMISecurityManager() ); 33 34 entries = serviceEntries; 35 LookupDiscovery lookupDiscovery = null; Set security manager
47
2001 Prentice Hall, Inc. All rights reserved. Outline 3.2 discover lookup services 3.3 wait until find lookup service(s) 36 37 // discover lookup services 38 try { 39 lookupDiscovery = new LookupDiscovery( 40 new String[] { domain } ); 41 } 42 43 // catch the IOException 44 catch ( IOException exception ) { 45 Debug.debugException( 46 "discover lookup service", exception ); 47 } 48 49 // install a listener 50 lookupDiscovery.addDiscoveryListener ( this ); 51 52 // wait until woken up by notification 53 try { 54 55 synchronized ( this ) { 56 wait(); 57 } 58 } 59 60 // handle exception waiting for notification 61 catch ( Exception exception ) { 62 Debug.debugException( 63 "wait for lookup service", exception ); 64 } 65 66 } // end DynamicServiceFinder constructor 67 Discover lookup services Wait until find lookup service(s)
48
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Get lookup service registrar 5. Ignore invalid lookup services 6. Get dynamic service proxy 6.1 specify service requirement 6.2 lookup dynamic service 68 // discover new lookup services 69 public void discovered ( DiscoveryEvent event ) 70 { 71 // get the proxy registrars for those services 72 registrars = event.getRegistrars(); 73 74 // wake up all waiting threads 75 synchronized ( this ) { 76 notifyAll(); 77 } 78 } 79 80 // discover invalid lookup services 81 public void discarded( DiscoveryEvent event) {} 82 83 // get dynamic service proxy 84 public Object getService() 85 { 86 // search lookup service to get dynamic service proxy 87 try { 88 ServiceTemplate template = new ServiceTemplate( 89 null, null, entries ); 90 Object service = registrars[ 0 ].lookup( template ); 91 92 return service; 93 } 94 95 // handle exception getting dynamic service proxy 96 catch ( Exception exception) { 97 Debug.debugException( "getting proxy", exception ); 98 } 99 100 return null; 101 102 } // end method getService 103 } Specify service requirement Lookup dynamic service Wake up all waiting threads when discover a lookup service
49
2001 Prentice Hall, Inc. All rights reserved. Outline Class PrinterClientGUI 1. Import packages 1 // Fig: PrinterClientGUI.java 2 // This application demonstrates how to obtain the proxy of 3 // a dynamic service and management policies, and call methods 4 // of the dynamic service. 5 package com.deitel.advjhtp1.jiro.DynamicService.client; 6 7 // Java core packages 8 import java.rmi.*; 9 import java.io.*; 10 import java.awt.*; 11 import java.awt.event.*; 12 import java.util.*; 13 import java.net.*; 14 15 // Java standard extensions 16 import javax.swing.*; 17 18 // Jini core package 19 import net.jini.core.lease.Lease; 20 import net.jini.core.event.*; 21 import net.jini.core.entry.Entry; 22 23 // Jini extension package 24 import net.jini.lease.LeaseRenewalManager; 25 import net.jini.lookup.entry.*; 26 27 // Jiro packages 28 import javax.fma.common.*; 29 import javax.fma.services.*; 30 import javax.fma.services.event.EventService; 31 import com.sun.jiro.util.*; 32 33 // Deitel packages 34 import com.deitel.advjhtp1.jiro.DynamicService.common.*; 35 import com.deitel.advjhtp1.jiro.DynamicService.service.*;
50
2001 Prentice Hall, Inc. All rights reserved. Outline 2. Declarations 3. Constructor 3.1 set security manager 3.2 obtain service proxy 3.3 subscribe to event service 3.4 GUI 36 37 public class PrinterClientGUI extends JFrame 38 implements RemoteEventListener { 39 40 private PrinterManagement printerManagementProxy; 41 private JTextArea printerStatusTextArea = 42 new JTextArea(); 43 private JTextArea printerEventTextArea = 44 new JTextArea(); 45 private Lease observerLease; 46 private LeaseRenewalManager leaseRenewalManager; 47 48 public PrinterClientGUI( String domain ) 49 { 50 super( "JIRO Printer Management Example" ); 51 52 // set security manager 53 if ( System.getSecurityManager() == null ) 54 System.setSecurityManager( new RMISecurityManager() ); 55 56 // obtain reference to proxy 57 printerManagementProxy = 58 getPrinterManagementProxy( domain ); 59 60 // subscribe to event service as an observer listener 61 subscriberObserver( domain ); 62 63 Container container = getContentPane(); 64 65 // status panel 66 JPanel printerStatusPanel = new JPanel(); 67 printerStatusPanel.setPreferredSize( 68 new Dimension( 512, 200 ) ); 69 JScrollPane statusScrollPane = new JScrollPane(); 70 statusScrollPane.setAutoscrolls( true ); Set security managerStatus panel displays printer status information
51
2001 Prentice Hall, Inc. All rights reserved. Outline 3.4 GUI 71 statusScrollPane.setPreferredSize( 72 new Dimension( 400, 150 ) ); 73 statusScrollPane.getViewport().add( 74 printerStatusTextArea, null ); 75 printerStatusPanel.add( statusScrollPane, null ); 76 77 // buttons panel 78 JPanel buttonPanel = new JPanel(); 79 buttonPanel.setPreferredSize( 80 new Dimension( 512, 200 ) ); 81 82 // define action for Check Status button 83 JButton checkStatusButton = 84 new JButton( "Check Status" ); 85 checkStatusButton.addActionListener( 86 87 new ActionListener() { 88 89 public void actionPerformed( ActionEvent event ) { 90 checkStatusButtonAction( event ); 91 } 92 } 93 ); 94 95 // define action for Remove Jammed Paper button 96 JButton cancelJobsButton = new JButton( 97 "Cancel Pending Print Jobs" ); 98 cancelJobsButton.addActionListener( 99 100 new ActionListener() { 101 102 public void actionPerformed( ActionEvent event ) { 103 cancelJobsButtonAction( event ); 104 } 105 } 106 ); Add Check Status buttonAdd Cancel Pending Print Jobs button
52
2001 Prentice Hall, Inc. All rights reserved. Outline 3.4 GUI 107 108 // add three buttons to the panel 109 buttonPanel.add( checkStatusButton, null ); 110 buttonPanel.add( cancelJobsButton, null ); 111 112 // events panel 113 JPanel printerEventPanel = new JPanel(); 114 printerEventPanel.setPreferredSize( 115 new Dimension( 512, 200) ); 116 JScrollPane eventsScrollPane = new JScrollPane(); 117 eventsScrollPane.setAutoscrolls( true ); 118 eventsScrollPane.setPreferredSize( 119 new Dimension( 400, 150 ) ); 120 eventsScrollPane.getViewport().add( 121 printerEventTextArea, null ); 122 printerEventPanel.add( eventsScrollPane, null ); 123 124 // initialize the text 125 printerStatusTextArea.setText( "Printer Status: ---\n" ); 126 printerEventTextArea.setText( "Events: --- \n" ); 127 128 // put all the panels together 129 container.add( printerStatusPanel, BorderLayout.NORTH ); 130 container.add( printerEventPanel, BorderLayout.SOUTH ); 131 container.add( buttonPanel, BorderLayout.CENTER ); 132 Event panel display printer event information
53
2001 Prentice Hall, Inc. All rights reserved. Outline 3.4 GUI 4 check printer status 133 // release observer listener and cancel scheduled task 134 // when window closing 135 addWindowListener( 136 137 new WindowAdapter() { 138 139 public void windowClosing( WindowEvent event ) 140 { 141 // release listener and cancel scheduled task 142 try { 143 leaseRenewalManager.remove( observerLease ); 144 } 145 146 // handle exception releasing observer listener 147 catch ( Exception exception ) { 148 exception.printStackTrace(); 149 } 150 151 // terminate the program 152 System.exit( 0 ); 153 154 } // end method windowClosing 155 156 } // end WindowAdapter constructor 157 158 ); // end addWindowListener 159 160 } // end PrinterManagementGUI constructor 161 162 // check print status 163 public void checkStatusButtonAction( ActionEvent event ) 164 { 165 boolean isOnline = false; 166 boolean isPaperJam = false; 167 boolean isPrinting = false; 168 int paperRemaining = 0; 169 String[] pendingJobs = null; Release observer listener Check printer status
54
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Check printer status 4.1 get status from service proxy 4.2 append output 170 171 // manage printer remotely 172 try { 173 174 // check if the printer is on line 175 isOnline = printerManagementProxy.isOnline(); 176 177 // check if the printer is paper jammed 178 isPaperJam = printerManagementProxy.isPaperJam(); 179 180 // check if the printing is pringint 181 isPrinting = printerManagementProxy.isPrinting(); 182 183 // get the paper tray 184 paperRemaining = printerManagementProxy.getPaperInTray(); 185 186 // get pending jobs 187 pendingJobs = 188 printerManagementProxy.getPendingPrintJobs(); 189 } 190 191 // handle exception calling dynamic service methods 192 catch ( Exception exception ) { 193 exception.printStackTrace(); 194 } 195 196 // status for the online condition 197 if ( isOnline ) 198 printerStatusTextArea.append( 199 "\nPrinter is ONLINE.\n" ); 200 else 201 printerStatusTextArea.append( 202 "\nPrinter is OFFLINE.\n" ); 203 Get status from service proxy Prepare output
55
2001 Prentice Hall, Inc. All rights reserved. Outline 4.2 append output 5. Cancel print jobs 204 // status for the paper jam condition 205 if ( isPaperJam ) 206 printerStatusTextArea.append( "Paper jammed.\n" ); 207 else 208 printerStatusTextArea.append( "No Paper Jam.\n" ); 209 210 // status for the printing condition 211 if ( isPrinting ) 212 printerStatusTextArea.append( 213 "Printer is currently printing.\n" ); 214 else 215 printerStatusTextArea.append( 216 "Printer is not printing.\n" ); 217 218 // status for paper tray condition 219 printerStatusTextArea.append( "Printer paper tray has " 220 + paperRemaining + " pages remaining.\n" ); 221 222 // number of pending jobs 223 printerStatusTextArea.append( "Number of pending jobs: " 224 + pendingJobs.length + "\n" ); 225 226 } // end method checkStatusButtonAction 227 228 // cancel print jobs 229 public void cancelJobsButtonAction( ActionEvent event ) 230 { 231 // cancel pending print jobs 232 try { 233 printerManagementProxy.cancelPendingPrintJobs(); 234 } 235 Append output Cancel print jobs
56
2001 Prentice Hall, Inc. All rights reserved. Outline 7. Get dynamic service proxy 7.1 specify service requirement 7.2 let DynamicServiceFinder get service proxy 8. Subscribe to event service 8.1 get event service 236 // handle exception canceling pending print jobs 237 catch ( Exception exception) { 238 exception.printStackTrace(); 239 } 240 241 } // end method cancelJobsButtonAction 242 243 // get dynamic service proxy 244 public PrinterManagement getPrinterManagementProxy( 245 String domain ) 246 { 247 Entry[] entries = new Entry[] { 248 new ServiceInfo( "PrinterManagementImpl", 249 "Deitel Association, Inc.", 250 "Deitel Association, Inc", 251 "1.0", "Model 0", "0.0.0.1" ) 252 }; 253 254 DynamicServiceFinder finder = new DynamicServiceFinder( 255 domain, entries ); 256 257 // return dynamic service proxy 258 return ( PrinterManagement ) finder.getService(); 259 260 } // end method getPrinterManagementProxy 261 262 // listener for events 263 public void subscriberObserver( String domain ) 264 { 265 // subscribe to printer events 266 try { 267 EventService eventService = 268 ServiceFinder.getEventService( domain ); 269 Specify service requirement Let DynamicServiceFinder get service proxy Get event service
57
2001 Prentice Hall, Inc. All rights reserved. Outline 8.2 subscribe to printer events 9. Receive event notification 10.main 270 // subscribe as an observing listener to certain event 271 RemoteEventListener listener = 272 new RemoteEventListenerImpl( this ); 273 observerLease = eventService.subscribeObserver( 274 ".Printer.Error", listener, null, 10 * 60 * 1000 ); 275 leaseRenewalManager = new LeaseRenewalManager( 276 observerLease, Lease.FOREVER, null ); 277 } 278 279 // handle exception subscribing to events 280 catch ( Exception exception ) { 281 exception.printStackTrace(); 282 } 283 } 284 285 // receive notification 286 public void notify( RemoteEvent event ) 287 { 288 String output = "\nEVENT: " + ( String ) event.getSource() 289 + "\n"; 290 SwingUtilities.invokeLater( 291 new TextAppender( printerEventTextArea, output ) ); 292 } 293 294 // method main 295 public static void main( String args[] ) 296 { 297 String domain = ""; 298 299 // get the domain 300 if ( args.length != 1 ) { 301 System.out.println( 302 "Usage: PrinterClientGUI Domain" ); 303 System.exit( 1 ); 304 } 305 else 306 domain = args[ 0 ]; Subscribe to printer events and renew listener’s lease Receive event notification
58
2001 Prentice Hall, Inc. All rights reserved. Outline 11. Inner class TextAppender 307 308 PrinterClientGUI client = new PrinterClientGUI( domain ); 309 client.setSize( 500, 500 ); 310 client.setVisible( true ); 311 312 } // end main method 313 314 // TextAppender appends text to a JTextArea. This Runnable 315 // object should be executed only using SwingUtilities 316 // methods invokeLater or invokeAndWait as it modifies 317 // a live Swing component. 318 private class TextAppender implements Runnable { 319 320 private String text; 321 private JTextArea textArea; 322 323 // TextAppender constructor 324 public TextAppender( JTextArea area, String newText ) 325 { 326 text = newText; 327 textArea = area; 328 } 329 330 // display new text in JTextArea 331 public void run() 332 { 333 // append new message 334 textArea.append( text ); 335 336 // move caret to end of messageArea to ensure new 337 // message is visible on screen 338 textArea.setCaretPosition( 339 textArea.getText().length() ); 340 } 341 342 } // end TextAppender inner class 343 } Inner class TextAppender appends text to a JTextArea
59
2001 Prentice Hall, Inc. All rights reserved. Outline Program output
60
2001 Prentice Hall, Inc. All rights reserved. Outline Program output
61
2001 Prentice Hall, Inc. All rights reserved. 25.8 Management Policies Policies –Automatic handle events –Encapsulation of a statement –Fine-grained control
62
2001 Prentice Hall, Inc. All rights reserved. Outline Interface OutofPaperPolicy 1. Declarations 1 // OutofPaperPolicy.java 2 // This class defines the interface for the dynamic service. 3 package com.deitel.advjhtp1.jiro.DynamicService.policy; 4 5 // Java core package 6 import java.rmi.*; 7 import java.util.*; 8 9 // Jini core package 10 import net.jini.core.event.*; 11 12 public interface OutofPaperPolicy extends RemoteEventListener { 13 14 public void stopPolicy( ) throws RemoteException; 15 }
63
2001 Prentice Hall, Inc. All rights reserved. Outline Class OutofPaperPolicyImpl 1. Import packages 1 // OutofPaperPolicyImpl.java 2 // Handles events generated by printer by registering 3 // as a responsible listener 4 package com.deitel.advjhtp1.jiro.DynamicService.policy; 5 6 // Java core packages 7 import java.io.Serializable; 8 import java.rmi.*; 9 import java.util.*; 10 11 // Java standard extensions 12 import javax.swing.*; 13 14 // Jini core packages 15 import net.jini.core.event.*; 16 import net.jini.core.entry.*; 17 import net.jini.core.lease.*; 18 19 // Jini extension packages 20 import net.jini.lease.LeaseRenewalManager; 21 import net.jini.lookup.entry.*; 22 23 // Jiro packages 24 import javax.fma.services.ServiceFinder; 25 import javax.fma.services.event.*; 26 import javax.fma.services.log.*; 27 import javax.fma.util.*; 28 import javax.fma.common.*; 29 import javax.fma.server.*; 30 31 // Deitel packages 32 import com.deitel.advjhtp1.jiro.DynamicService.service.*; 33 import com.deitel.advjhtp1.jiro.DynamicService.common.*; 34
64
2001 Prentice Hall, Inc. All rights reserved. Outline 2. Declarations 3. Constructor 3.1 obtain reference to dynamic service 3.2 obtain reference to static services 3.3 subscribe to printer out-of-paper policy 35 public class OutofPaperPolicyImpl 36 implements OutofPaperPolicy { 37 38 private Lease listenerLease; 39 private LeaseRenewalManager leaseRenewalManager; 40 41 private LogService logService; 42 private PrinterEventListener listener; 43 private PrinterManagement printerManagementProxy; 44 45 // OutofPaperPolicyImpl constructor 46 public OutofPaperPolicyImpl() 47 { 48 // subscribe as an responsible listener to certain event 49 listener = new PrinterEventListener( this ); 50 51 // start the OutofPaper management policy 52 try { 53 54 // obtain reference to dynamic service entry point 55 printerManagementProxy = getPrinterManagementProxy(); 56 57 // obtain reference to log service 58 logService = ServiceFinder.getLogService(); 59 60 // obtain reference to log service 61 EventService eventService = 62 ServiceFinder.getEventService(); 63 64 // subscribe as responsible listener 65 listenerLease = 66 eventService.subscribeResponsibleBefore( 67 ".Printer.Error.OutofPaper", null, listener, 68 "OutofPaperEventListener", null, Lease.FOREVER ); 69 Obtain reference to dynamic service Obtain reference to static services Subscribe to printer out-of-paper policy as responsible listener
65
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Stop the policy 70 // renew lease indefinitely 71 leaseRenewalManager = new LeaseRenewalManager( 72 listenerLease, Lease.FOREVER, null ); 73 74 } // end try 75 76 // handle exception starting policy 77 catch ( Exception exception ) { 78 System.out.println( "OutofPaperPolicyImpl: " + 79 "Exception occurred when starting policy." ); 80 System.out.println( "Please read debug file... \n" ); 81 Debug.debugException( 82 "starting LowTonerPolicy", exception ); 83 } 84 85 System.out.println( "OutofPaperPolicyImpl: started." ); 86 87 } // end OutofPaperPolicyImpl constructor 88 89 // stop OutofPaperPolicyImpl 90 public void stopPolicy() 91 { 92 // stopping OutofPaper management policy 93 try { 94 95 // expire lease 96 leaseRenewalManager.cancel( listenerLease ); 97 System.out.println( "OutofPaperPolicyImpl: stopping." ); 98 } 99 Expire listener’s lease to stop the policy
66
2001 Prentice Hall, Inc. All rights reserved. Outline 5. Receive event notification 5.1 identify event source 100 // handle exception canceling lease 101 catch ( Exception exception ) { 102 System.out.println( "OutofPaperPolicyImpl: " + 103 "Exception occurred when canceling lease." ); 104 System.out.println( "Please read debug file... \n" ); 105 Debug.debugException( 106 "stopping OutofPaper policy", exception ); 107 } 108 } 109 110 // receive notification calls 111 public void notify( RemoteEvent remoteEvent ) 112 throws UnknownEventException, RemoteException, 113 EventNotHandledException 114 { 115 Object sourceObject = null; 116 117 // event source 118 try { 119 120 // get event source 121 sourceObject = remoteEvent.getSource(); 122 } 123 124 // handle exception getting event source 125 catch ( Exception exception ) { 126 System.out.println( "OutofPaperPolicyImpl: " + 127 "Exception occurred when getting event source." ); 128 System.out.println( "Please read debug file... \n" ); 129 Debug.debugException( 130 "getting event source", exception ); 131 } 132 Receive event notification Identify event source
67
2001 Prentice Hall, Inc. All rights reserved. Outline 5.2 automatic handle out-of-paper event 5.3 log handling message 133 // definitely not from our printer 134 if ( !( sourceObject instanceof String ) ) { 135 136 throw new EventNotHandledException(); 137 } 138 139 // obtain String value 140 String source = ( String ) sourceObject; 141 142 // verify origin of event 143 if ( source.equals( "com.deitel.advjhtp1.jiro." 144 + "DynamicService.printer.ErrorMessage=OutofPaper") ) { 145 146 System.out.println( "OutfPaperPolicy: " 147 + "handling OutofPaperEvent..." ); 148 149 // take action 150 try { 151 152 // replenish paper tray 153 printerManagementProxy.addPaper( 50 ); 154 155 // generate the log message parameters 156 Serializable params[] = new Serializable[ 2 ]; 157 params[ 0 ] = source; 158 params[ 1 ] = new Date(); 159 160 // generate localizable message 161 LocalizableMessage localizableMessage = 162 new LocalizableMessage( 163 OutofPaperPolicyImpl.class, 164 "Action", params, Locale.US ); 165 Automatic handle out-of-paper event Log handling messageVerity origin of event
68
2001 Prentice Hall, Inc. All rights reserved. Outline 5.3 log handling message 166 // generate log message 167 LogMessage logMessage = new LogMessage( 168 localizableMessage, LogMessage.TRACE 169 + ".OutofPaperEvent." + source, null ); 170 171 // log action message 172 logService.log( logMessage ); 173 174 } // end try 175 176 // handle exception posting log message 177 catch ( Exception exception ) { 178 System.out.println( "OutofPaperPolicyImpl: " + 179 "Exception occurred when posting log message." ); 180 System.out.println( "Please read debug file...\n" ); 181 Debug.debugException( "log service", exception ); 182 } 183 184 } // end if 185 186 // not event from our printer 187 else { 188 189 System.out.println( "OutfPaperPolicy: " + 190 " NOT handling OutofPaperEvent..." ); 191 192 // responsible listener requirement 193 // when not handling event. 194 throw new EventNotHandledException(); 195 } 196 197 } // end method notify 198 Log event handled message Not event from out printer
69
2001 Prentice Hall, Inc. All rights reserved. Outline 6. Get dynamic service proxy 6.1 specify service requirement 6.2 let DynamicServiceFinder get service proxy 7. Implement getLookupEntries to declare the class as dynamic service resource file 199 // get dynamic services proxies 200 public PrinterManagement getPrinterManagementProxy() 201 { 202 Entry[] entries = new Entry[] { 203 new ServiceInfo( "PrinterManagementImpl", 204 "Deitel Association, Inc.", 205 "Deitel Association, Inc", 206 "1.0", "Model 0", "0.0.0.1" ) 207 }; 208 209 String domain = System.getProperty( "javax.fma.domain" ); 210 DynamicServiceFinder finder = 211 new DynamicServiceFinder( domain, entries ); 212 213 // return proxy 214 return ( PrinterManagement ) finder.getService(); 215 216 } // end method getPrinterManagementProxy 217 218 // defines class as dynamic service during deployment 219 private Entry[] getLookupEntries() 220 { 221 return ( new Entry[] { 222 new ServiceInfo( "OutofPaperPolicyImpl", 223 "Deitel Association, Inc.", 224 "Deitel Association, Inc", 225 "1.0", "Model 0", "0.0.0.1" ) 226 } 227 ); 228 } 229 } 1 Action = Added paper to {0} on {1}. Fig. 25.19 Property file for OutofPaperPolicyImpl. Specify service requirement Let DynamicServiceFinder get service proxy Implement getLookupEntries to declare the class as dynamic service
70
2001 Prentice Hall, Inc. All rights reserved. Outline Interface LowTonerPolicy 1. Declarations 1 // Fig: LowTonerPolicy.java 2 // This class defines the interface for the dynamic service. 3 package com.deitel.advjhtp1.jiro.DynamicService.policy; 4 5 // Java core package 6 import java.rmi.*; 7 import java.util.*; 8 9 // Jini core package 10 import net.jini.core.event.*; 11 12 public interface LowTonerPolicy extends RemoteEventListener { 13 14 public void stopPolicy() throws RemoteException; 15 }
71
2001 Prentice Hall, Inc. All rights reserved. Outline Class LowTonerPolicyImpl 1. Import packages 1 // LowTonerPolicyImpl.java 2 // Handles events generated by printer by registering 3 // as a responsible listener 4 package com.deitel.advjhtp1.jiro.DynamicService.policy; 5 6 // Java core packages 7 import java.io.Serializable; 8 import java.rmi.*; 9 import java.util.*; 10 11 // Java standard extensions 12 import javax.swing.*; 13 14 // Jini core packages 15 import net.jini.core.event.*; 16 import net.jini.core.entry.*; 17 import net.jini.core.lease.*; 18 19 // Jini extension packages 20 import net.jini.lease.LeaseRenewalManager; 21 import net.jini.lookup.entry.*; 22 23 // Jiro packages 24 import javax.fma.services.*; 25 import javax.fma.services.event.*; 26 import javax.fma.services.log.*; 27 import javax.fma.util.*; 28 import javax.fma.common.*; 29 import javax.fma.server.*; 30 31 // Deitel packages 32 import com.deitel.advjhtp1.jiro.DynamicService.service.*; 33 import com.deitel.advjhtp1.jiro.DynamicService.common.*; 34
72
2001 Prentice Hall, Inc. All rights reserved. Outline 2. Declarations 3. Constructor 3.1 obtain reference to dynamic service 3.2 obtain reference to static services 3.3 subscribe to printer low-toner policy 35 public class LowTonerPolicyImpl 36 implements LowTonerPolicy { 37 38 private Lease listenerLease; 39 private LeaseRenewalManager leaseRenewalManager; 40 41 private LogService logService; 42 private PrinterEventListener listener; 43 private PrinterManagement printerManagementProxy; 44 45 // LowTonerPolicyImpl constructor 46 public LowTonerPolicyImpl() 47 { 48 // subscribe as an responsible listener to certain event 49 listener = new PrinterEventListener( this ); 50 51 // start the LowToner management policy 52 try { 53 54 // obtain referrence to dynamic service entry point 55 printerManagementProxy = getPrinterManagementProxy(); 56 57 // obtain referrence to log service 58 logService = ServiceFinder.getLogService(); 59 60 // obtain referrence to log service 61 EventService eventService = 62 ServiceFinder.getEventService(); 63 64 // subscribe as responsible listener 65 listenerLease = 66 eventService.subscribeResponsibleBefore( 67 ".Printer.Error.LowToner", null, listener, 68 "LowTonerEventListener", null, Lease.FOREVER ); 69 Obtain reference to dynamic service Obtain reference to static services Subscribe to printer out-of-paper policy as responsible listener
73
2001 Prentice Hall, Inc. All rights reserved. Outline 4. Stop the policy 70 // renew lease indefinitely 71 leaseRenewalManager = new LeaseRenewalManager( 72 listenerLease, Lease.FOREVER, null ); 73 } 74 75 // handle exception starting policy 76 catch ( Exception exception ) { 77 System.out.println( "LowTonerPolicyImpl: " + 78 "Exception occurred when starting policy." ); 79 System.out.println( "Please read debug file... \n" ); 80 Debug.debugException( 81 "starting LowTonerPolicyImpl", exception ); 82 } 83 84 System.out.println( "LowTonerPolicyImpl: started." ); 85 86 } // end LowTonerPolicyImpl constructor 87 88 // stop OutofPaperPolicy 89 public void stopPolicy() 90 { 91 // stop the LowToner management policy 92 try { 93 94 // expire lease 95 leaseRenewalManager.cancel( listenerLease ); 96 System.out.println( "LowTonerPolicyImpl: stopping." ); 97 } 98 Expire listener’s lease to stop the policy
74
2001 Prentice Hall, Inc. All rights reserved. Outline 5. Receive event notification 5.1 identify event source 99 // handle exception canceling lease 100 catch ( Exception exception ) { 101 System.out.println( "LowTonerPolicyImpl: " + 102 "Exception occurred when canceling lease." ); 103 System.out.println( "Please read debug file... \n" ); 104 Debug.debugException( 105 "stopping LowTonerPolicyImpl", exception ); 106 } 107 } 108 109 // receive notification calls 110 public void notify( RemoteEvent remoteEvent ) 111 throws UnknownEventException, RemoteException, 112 EventNotHandledException 113 { 114 // event source 115 Object sourceObject = null; 116 117 // get event source 118 try { 119 sourceObject = remoteEvent.getSource(); 120 } 121 122 // handle exception getting event source 123 catch ( Exception exception ) { 124 System.out.println( "LowTonerPolicyImpl: " + 125 "Exception occurred when getting event source." ); 126 System.out.println( "Please read debug file... \n" ); 127 Debug.debugException( 128 "getting event source", exception ); 129 } 130 Receive event notificationIdentify event source
75
2001 Prentice Hall, Inc. All rights reserved. Outline 5.2 automatic handle low-toner event 5.3 log handling message 131 // definitely not from our printer 132 if ( !( sourceObject instanceof String ) ) { 133 134 throw new EventNotHandledException(); 135 } 136 137 // obtain String value 138 String source = ( String ) sourceObject; 139 140 // verify origin of event 141 if ( source.equals( "com.deitel.advjhtp1.jiro." 142 + "DynamicService.printer.ErrorMessage=LowToner" ) ) { 143 144 System.out.println( 145 "LowTonerPolicyImpl: handling LowTonerEvent..." ); 146 147 // take action 148 try { 149 150 // replenish toner cartridge 151 printerManagementProxy.addToner(); 152 153 // generate the log message parameters 154 Serializable params[] = new Serializable[ 2 ]; 155 params[ 0 ] = source; 156 params[ 1 ] = new Date(); 157 158 // generate localizable message 159 LocalizableMessage localizableMessage = 160 new LocalizableMessage( 161 LowTonerPolicyImpl.class, "Action", 162 params, Locale.US ); 163 Automatic handle low-toner event Log handling messageVerify origin of event
76
2001 Prentice Hall, Inc. All rights reserved. Outline 5.3 log handling message 164 // generate log message 165 LogMessage logMessage = new LogMessage( 166 localizableMessage, LogMessage.TRACE 167 + ".LowTonerEvent." + source, null ); 168 169 // log action message 170 logService.log( logMessage ); 171 172 } // end try 173 174 // handle exception posting log message 175 catch ( Exception exception ) { 176 System.out.println( "LowTonerPolicyImpl:" + 177 "Exception occurred when taking action." ); 178 System.out.println( "Please read debug file...\n" ); 179 Debug.debugException( "take action", exception ); 180 } 181 182 } // end if 183 184 // not event from our printer 185 else { 186 System.out.println( "LowTonerPolicyImpl: " 187 + "NOT handling OutofPaperEvent..." ); 188 189 // responsible listener requirement 190 // when not handling event. 191 throw new EventNotHandledException(); 192 } 193 194 } // end method notify 195 Log handling message Not event from our printer
77
2001 Prentice Hall, Inc. All rights reserved. Outline 6. Get dynamic service proxy 6.1 specify service requirement 6.2 let DynamicServiceFinder get service proxy 7. Implement getLookupEntries to declare the class as dynamic service resource file 196 // get dynamic services proxies 197 public PrinterManagement getPrinterManagementProxy() 198 { 199 Entry[] entries = new Entry[] { 200 new ServiceInfo( "PrinterManagementImpl", 201 "Deitel Association, Inc.", 202 "Deitel Association, Inc", 203 "1.0", "Model 0", "0.0.0.1" ) 204 }; 205 206 String domain = System.getProperty( "javax.fma.domain" ); 207 DynamicServiceFinder finder = 208 new DynamicServiceFinder( domain, entries ); 209 210 // return proxy 211 return ( PrinterManagement ) finder.getService(); 212 213 } // end method getPrinterManagementProxy 214 215 // defines class as dynamic service during deployment 216 private Entry[] getLookupEntries() 217 { 218 return ( new Entry[] { 219 new ServiceInfo( "LowTonerPolicyImpl", 220 "Deitel Association, Inc.", 221 "Deitel Association, Inc", 222 "1.0", "Model 0", "0.0.0.1" ) 223 } 224 ); 225 } 226 } 1 Action = Added toner to {0} on {1}. Fig. 25.22 Property file for LowTonerPolicyImpl. Specify service requirement Let DynamicServiceFinder get service proxy Implement getLookupEntries to declare the class as dynamic service
78
2001 Prentice Hall, Inc. All rights reserved. 25.8.1 Policy-Management Deployment Deploy management policies with dynamic service –Restart Jiro –Deploy management policies with dynamic service Create JAR files Use Jarpackw tool Use Jardeploy tool Start management policies
79
2001 Prentice Hall, Inc. All rights reserved. 25.8.1 Policy-Management Deployment
80
2001 Prentice Hall, Inc. All rights reserved. 25.8.1 Policy-Management Deployment
81
2001 Prentice Hall, Inc. All rights reserved. 25.8.1 Policy-management Deployment
82
2001 Prentice Hall, Inc. All rights reserved. 25.8.1 Policy-Management Deployment
83
2001 Prentice Hall, Inc. All rights reserved. Outline Class PoliciesStarter 1. Constructor 1.1 set security manager 1.2 obtain station address 1 // Fig: PoliciesStarter.java 2 // This application demonstrates how to obtain the proxies of 3 // management policies. 4 package com.deitel.advjhtp1.jiro.DynamicService.client; 5 6 // Java core package 7 import java.rmi.*; 8 9 // Jiro packages 10 import javax.fma.common.*; 11 12 // Deitel packages 13 import com.deitel.advjhtp1.jiro.DynamicService.policy.*; 14 15 public class PoliciesStarter { 16 17 // PoliciesStarter constructor 18 public PoliciesStarter( String domain ) { 19 20 OutofPaperPolicy paperPolicyProxy; 21 LowTonerPolicy tonerPolicyProxy; 22 23 // set security manager 24 if ( System.getSecurityManager() == null ) 25 System.setSecurityManager( new RMISecurityManager() ); 26 27 // obtain station address 28 StationAddress stationAddress = 29 new StationAddress( domain, 30 null, null, null, null, null, null, null ); 31 Set security managerObtain station address
84
2001 Prentice Hall, Inc. All rights reserved. Outline 1.3 instantiate management policies 2. main 32 // get the proxies of management policies 33 try { 34 paperPolicyProxy = 35 new OutofPaperPolicyImplProxy( stationAddress ); 36 tonerPolicyProxy = 37 new LowTonerPolicyImplProxy( stationAddress ); 38 } 39 40 // handle exception getting proxies and starting policies 41 catch ( RemoteException exception ) { 42 exception.printStackTrace(); 43 } 44 45 } // end PoliciesStarter constructor 46 47 // method main 48 public static void main( String args[] ) 49 { 50 String domain = ""; 51 52 // get the domain name 53 if ( args.length != 1 ) { 54 System.out.println( 55 "Usage: PoliciesStarter Domain" ); 56 System.exit( 1 ); 57 } 58 else 59 domain = args[ 0 ]; 60 61 PoliciesStarter policiesStarter = 62 new PoliciesStarter( domain ); 63 64 } // end main method 65 } Instantiate management policies
85
2001 Prentice Hall, Inc. All rights reserved. Outline Program output
86
2001 Prentice Hall, Inc. All rights reserved. Outline viewlog tool output
87
2001 Prentice Hall, Inc. All rights reserved. Outline viewlog tool output
88
2001 Prentice Hall, Inc. All rights reserved. 25.9 Closing Notes on the Printer Management Solution Entry point object Management entity Management policies Management console
89
2001 Prentice Hall, Inc. All rights reserved. 25.10 Internet and World Wide Web Resources jiro.com/documentcenter/ www.jiro.com/overview/ sunjweb-001.jiro.com/faqs/ www.jiro.com/education/recipes/ www.jiro.com/education/recipes/service/ www.sce.carleton.ca/netmanage/NMfor90s/SimpleNM.html sunjweb-001.jiro.com/cgi-bin/Ultimate.cgi?action=intro
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.