2001 prentice hall, inc. all rights reserved. chapter 23 - javaspaces outline 23.1 introduction 23.2...

86
2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service 23.4 Discovering the JavaSpaces Service 23.5 JavaSpace Interface 23.6 Defining an Entry 23.7 Write Operation 23.8 Read and Take Operations 23.8.1 Read Operation 23.8.2 Take Operation 23.9 Notify Operation 23.10 Method Snapshot 23.11 Updating Entries with Jini Transaction Service 23.11.1 Defining User Interface 23.11.2 Discovering the TransactionManager Service 23.11.3 Updating an Entry 23.12 Case Study: Distributed Image Processing 23.12.1 Defining an Image Processor 23.12.2 Partitioning an Image into Smaller Pieces 23.12.3 Compiling and Running the example 23.13 Internet and World Wide Web Resources

Upload: agnes-reynolds

Post on 25-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

Chapter 23 - JavaSpacesOutline23.1 Introduction23.2 JavaSpaces Service Properties23.3 JavaSpaces Service23.4 Discovering the JavaSpaces Service 23.5 JavaSpace Interface 23.6 Defining an Entry23.7 Write Operation23.8 Read and Take Operations

23.8.1 Read Operation23.8.2 Take Operation

23.9 Notify Operation23.10 Method Snapshot23.11 Updating Entries with Jini Transaction Service

23.11.1  Defining User Interface 23.11.2 Discovering the

TransactionManager Service23.11.3 Updating an Entry

23.12 Case Study: Distributed Image Processing23.12.1 Defining an Image Processor23.12.2 Partitioning an Image into Smaller

Pieces23.12.3 Compiling and Running the

example23.13 Internet and World Wide Web Resources

Page 2: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.1 Introduction

• Distributed systems communication – Message Queues

– JavaSpace technology

• JavaSpace feature– Simple

– Jini

– Transaction Manager

– RMI

Page 3: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.2 JavaSpaces Service Properties

• Six properties– A Jini Service

– Concurrent

– Persistent

– Template matching

– Atomic operations

– Shared

Page 4: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.3 JavaSpaces Service

• Distributed shared storage for Java objects• Restrictions on Java objects

– Implement net.jini.core.entry.Entry interface

– A public no-argument constructor

– Public fields

– No primitive type fields

• Two JavaSpaces service– Transient JavaSpace

– Persistent JavaSpace

Page 5: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.4 Discovering the JavaSpaces Service

• Start persistent JavaSpaces service– Web server

– rmid

– Lookup service

• Obtain access to the JavaSpaces service

Page 6: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // JavaSpaceFinder.java2 // This application unicast discovers the JavaSpaces service.3 package com.deitel.advjhtp1.javaspace.common;4 5 // Jini core packages6 import net.jini.core.discovery.LookupLocator;7 import net.jini.core.lookup.*;8 import net.jini.core.entry.Entry;9 10 // Jini extension package11 import net.jini.space.JavaSpace;12 13 // Java core packages14 import java.io.*;15 import java.rmi.*;16 import java.net.*;17 18 // Java extension package19 import javax.swing.*;20 21 public class JavaSpaceFinder {22 23 private JavaSpace space;24 25 public JavaSpaceFinder( String jiniURL )26 {27 LookupLocator locator = null;28 ServiceRegistrar registrar = null;29 30 System.setSecurityManager( new RMISecurityManager() );31

ClassJavaSpaceFinder

1. Import packages

2. Declaration

3. Constructor

3.1 Set security manager

Set security manager

Page 7: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline32 // get lookup service locator at "jini://hostname" 33 // use default port and registrar of the locator34 try {35 locator = new LookupLocator( jiniURL );36 registrar = locator.getRegistrar();37 } 38 39 // handle exception invalid jini URL40 catch ( MalformedURLException malformedURLException ) {41 malformedURLException.printStackTrace();42 }43 44 // handle exception I/O45 catch ( java.io.IOException ioException ) {46 ioException.printStackTrace();47 }48 49 // handle exception finding class50 catch ( ClassNotFoundException classNotFoundException ) {51 classNotFoundException.printStackTrace();52 }53 54 // specify the service requirement55 Class[] types = new Class[] { JavaSpace.class };56 ServiceTemplate template = 57 new ServiceTemplate( null, types, null );58 59 // find service 60 try {61 space = 62 ( JavaSpace ) registrar.lookup( template );63 } 64

3.2 get lookup locator

3.3 specify template to match

3.4 find service

Matching template

Find JavaSpace

Get lookup locator

Page 8: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

65 // handle exception getting JavaSpace66 catch ( RemoteException remoteException ) {67 remoteException.printStackTrace();68 }69 70 // if does not find any matching service71 if ( space == null ) {72 System.out.println( "No matching service" );73 }74 75 } // end JavaSpaceFinder constructor76 77 public JavaSpace getJavaSpace()78 {79 return space;80 }81 }

4. Return Javaspace

Page 9: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.5 JavaSpace Interface

• Four operations– Notify operation: notify

– Read operation: read readIfExists

– Take operation: take takeIfExists

– Write operation: write

• One method– Method snapshot

Page 10: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.6 Defining an Entry

• Define an Entry– Constructors

• Public

• No-argument

– Fields• Public

• No primitive types

– methods

Page 11: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

1 // Fig. 23.2: AttendeeCounter.java2 // This class defines the AttendeeCounter Entry object.3 package com.deitel.advjhtp1.javaspace.common;4 5 import net.jini.core.entry.Entry;6 7 public class AttendeeCounter implements Entry {8 9 public String seminarDay;10 public Integer attendeeCounter;11 12 // empty constructor13 public AttendeeCounter() {}14 15 // constructor has a single String input16 public AttendeeCounter( String day )17 {18 seminarDay = day;19 }20 }

ClassAttendeeCounter

1. Declarations

2. Empty constructor

3. Methods

Implements Entry interface

Use the Integer wrapper class to wrap the int primitive type

No-argument constructor

Page 12: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.7 Write Operation

• Method write takes three arguments– An Entry– A Transaction

– A long value that specifies lease time

• Method write throws two exceptions– RemoteException– TransactionException

Page 13: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // WriteOperation.java2 // This application initializes an new Entry object, 3 // and puts this Entry to the JavaSpace.4 package com.deitel.advjhtp1.javaspace.write;5 6 // Jini core packages7 import net.jini.core.lease.Lease;8 import net.jini.core.transaction.TransactionException;9 10 // Jini extension package11 import net.jini.space.JavaSpace;12 13 // Java core package14 import java.rmi.RemoteException;15 16 // Java extension package17 import javax.swing.*;18 19 // Deitel package20 import com.deitel.advjhtp1.javaspace.common.*;21 22 public class WriteOperation {23 24 private JavaSpace space;25 private static final String[] days = { "Monday", "Tuesday",26 "Wednesday", "Thursday", "Friday" };27 private String output = "\n";28

Class WriteOperation

1. Import packages

2. Declarations

Page 14: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline29 // WriteOperation constructor30 public WriteOperation( String hostname )31 {32 // get JavaSpace33 String jiniURL = "jini://" + hostname;34 JavaSpaceFinder findtool = new JavaSpaceFinder( jiniURL );35 space = findtool.getJavaSpace();36 }37 38 // deposit new Entry to JavaSpace39 public void writeEntry( String day )40 {41 // initialize AttendeeCounter Entry and deposit 42 // Entry object in JavaSpace43 try {44 AttendeeCounter counter = new AttendeeCounter( day );45 counter.counter = new Integer( 0 );46 space.write( counter, null, Lease.FOREVER );47 48 output += "Initialize the Entry: \n";49 output += " Day: " + day + "\n";50 output += " Count: 0\n";51 }52 53 // handle exception network failure 54 catch ( RemoteException exception ) {55 exception.printStackTrace();56 }57 58 // handle exception invalid transaction59 catch ( TransactionException exception ) {60 exception.printStackTrace();61 }62 }63

3. Constructor

3.1 obtain JavaSpaces service

4. Write Entry

4.1 initialize Entry

4.2 write Entry into JavaSpace

Write Entry into JavaSpace

Obtain JavaSpaces service

Output displayed to the user

Page 15: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline64 // show output65 public void showOutput()66 {67 JTextArea outputArea = new JTextArea();68 outputArea.setText( output );69 JOptionPane.showMessageDialog( null, outputArea, 70 "WriteOperation Output", 71 JOptionPane.INFORMATION_MESSAGE );72 73 // terminate program74 System.exit( 0 );75 }76 77 // method main78 public static void main( String args[] )79 {80 // get hostname81 if ( args.length != 1 ) {82 System.out.println( 83 "Usage: WriteOperation hostname" );84 System.exit( 1 );85 }86 87 // get user input day88 String day = ( String ) JOptionPane.showInputDialog( 89 null, "Select Day", "Day Selection", 90 JOptionPane.QUESTION_MESSAGE, null, days, days[ 0 ] );91 92 // write Entry93 WriteOperation write = new WriteOperation( args[ 0 ] );94 write.writeEntry( day );95 96 write.showOutput();97 98 } // end method main99 }

5. Show output

5.1 GUI

6. Main

6.1 get hostname

6.2 GUI

Displays output to a message dialog

Get user input day

Page 16: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

Program output

Page 17: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.8 Read and Take Operations

• Template matching– Public fields

– Null acts as wildcards

• Read operation– Method read and readIfExists

• Take operation– Method take and takeIfExists

Page 18: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.8.1 Read Operation

• Entrys stay in the JavaSpace• Method read and readIfExists

– Common• Three arguments:

– An Entry

– A Transaction

– A wait time

– Difference• Method read blocks before returning null• Method readIfExists returns null immediately

Page 19: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // ReadOperation.java2 // This application reads an Entry from the JavaSpace and3 // displays the Entry information.4 package com.deitel.advjhtp1.javaspace.read;5 6 // Jini core packages7 import net.jini.core.transaction.TransactionException;8 import net.jini.core.entry.UnusableEntryException;9 10 // Jini extension package11 import net.jini.space.JavaSpace;12 13 // Java core packages14 import java.rmi.RemoteException;15 import java.lang.InterruptedException;16 17 // Java extension package18 import javax.swing.*;19 20 // Deitel package21 import com.deitel.advjhtp1.javaspace.common.*;22 23 public class ReadOperation {24 25 private JavaSpace space;26 private static final String[] days = { "Monday", "Tuesday",27 "Wednesday", "Thursday", "Friday" };28 private String output = "\n";29

ClassReadOperation

1. Import packages

2. Declarations

Page 20: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline30 // constructor gets JavaSpace31 public ReadOperation( String hostname )32 {33 // get JavaSpace34 String jiniURL = "jini://" + hostname;35 JavaSpaceFinder findtool = new JavaSpaceFinder( jiniURL );36 space = findtool.getJavaSpace();37 }38 39 // read Entry from JavaSpace40 public void readEntry( String day )41 {42 // specify matching template, read template43 // from the JavaSpace and output the Entry information44 try {45 46 // read Entry from JavaSpace47 AttendeeCounter counter = new AttendeeCounter( day );48 AttendeeCounter resultCounter = ( AttendeeCounter ) 49 space.read( counter, null, JavaSpace.NO_WAIT );50 51 if ( resultCounter == null ) {52 output += "Sorry, cannot find an Entry for "53 + day + "!\n";54 }55 else {56 57 // get Entry information58 output += "Count Information:\n";59 output += " Day: " + resultCounter.seminarDay;60 output += "\n";61 output += " Count: " 62 + resultCounter.counter.intValue() + "\n";63 }64 }

3. Obtain JavaSpace

4. Read Entry

4.1 specify template

4.2 read Entry

4.3 append output

Specify template

Read Entry

Could not find a matching Entry

Find a matching Entry

Page 21: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline65 66 // handle exception network failure67 catch ( RemoteException exception ) {68 exception.printStackTrace();69 }70 71 // handle exception invalid transaction72 catch ( TransactionException exception ) {73 exception.printStackTrace();74 }75 76 // handle exception unusable Entry 77 catch ( UnusableEntryException exception ) {78 exception.printStackTrace();79 }80 81 // handle exception interrupting82 catch ( InterruptedException exception ) {83 exception.printStackTrace();84 }85 86 } // end method readEntry87 88 // show output89 public void showOutput()90 {91 JTextArea outputArea = new JTextArea();92 outputArea.setText( output );93 JOptionPane.showMessageDialog( null, outputArea, 94 "ReadOperation Output", 95 JOptionPane.INFORMATION_MESSAGE );96 97 // terminate program98 System.exit( 0 );99 }100

4.4 Handle exceptions

5 Show output

5.1 GUI

Display the output to a message dialog

Page 22: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline101 // method main102 public static void main( String args[] )103 {104 // get hostname105 if ( args.length != 1 ) {106 System.out.println( 107 "Usage: ReadOperation hostname" );108 System.exit( 1 );109 }110 111 // get user input day112 String day = ( String ) JOptionPane.showInputDialog( 113 null, "Select Day", "Day Selection", 114 JOptionPane.QUESTION_MESSAGE, null, days, days[ 0 ] );115 116 // read Entry117 ReadOperation read = new ReadOperation( args[ 0 ] );118 read.readEntry( day );119 120 read.showOutput();121 122 } // end method main123 }

6. main

Program output

Get user input day from a input dialog

Page 23: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.8.2 Take Operation

• Obtains and removes Entrys from the JavaSpace

• Method take similar to method read• Method takeIfExists similar to method readIfExists

Page 24: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // TakeOperation.java2 // This application removes an Entry from the JavaSpace.3 package com.deitel.advjhtp1.javaspace.take;4 5 // Jini core packages6 import net.jini.core.transaction.TransactionException;7 import net.jini.core.entry.UnusableEntryException;8 9 // Jini extension package10 import net.jini.space.JavaSpace;11 12 // Java core packages13 import java.rmi.RemoteException;14 15 // Java extension package16 import javax.swing.*;17 18 // Deitel package19 import com.deitel.advjhtp1.javaspace.common.*;20 21 public class TakeOperation {22 23 private JavaSpace space = null;24 private static final String[] days = { "Monday", "Tuesday",25 "Wednesday", "Thursday", "Friday" };26 private String output = "\n";27

Class TakeOperation

1. Import packages

2. Declarations

Page 25: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline28 // constructor gets JavaSpace29 public TakeOperation( String hostname )30 {31 // get JavaSpace32 String jiniURL = "jini://" + hostname;33 JavaSpaceFinder findtool = new JavaSpaceFinder( jiniURL );34 space = findtool.getJavaSpace();35 }36 37 // remove Entry from JavaSpace38 public void TakeAnEntry( String day )39 {40 AttendeeCounter resultCounter = null;41 42 // specify matching template, remove template43 // from JavaSpace44 try { 45 AttendeeCounter count = new AttendeeCounter( day );46 resultCounter = ( AttendeeCounter ) space.take( count,47 null, JavaSpace.NO_WAIT );48 49 if ( resultCounter == null) {50 output += "No Entry for " + day51 + " is available from the JavaSpace.\n";52 }53 else {54 output += "Entry is taken away from ";55 output += "the JavaSpace successfully.\n";56 }57 }58 59 // handle exception network failure60 catch ( RemoteException exception ) {61 exception.printStackTrace();62 }63

3. Obtain JavaSpace

4. Remove Entry

4.1 specify template

4.2 remove Entry

4.3 append output

4.4 catch exceptions

Obtain JavaSpaces service

Specify template

Remove Entry

Page 26: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline64 // handle exception invalid transaction65 catch ( TransactionException exception ) {66 exception.printStackTrace();67 }68 69 // handle exception unusable entry70 catch ( UnusableEntryException exception ) {71 exception.printStackTrace();72 }73 74 // handle exception interrupt75 catch ( InterruptedException exception ) {76 exception.printStackTrace();77 }78 79 } // end method TakeAnEntry80 81 // show output82 public void showOutput()83 {84 JTextArea outputArea = new JTextArea();85 outputArea.setText( output );86 JOptionPane.showMessageDialog( null, outputArea, 87 "TakeOperation Output", 88 JOptionPane.INFORMATION_MESSAGE );89 90 // terminate program91 System.exit( 0 );92 }93

5. Show output

Display output to a message dialog

Page 27: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline94 public static void main( String args[] )95 {96 // get hostname97 if ( args.length != 1 ) {98 System.out.println( 99 "Usage: TakeOperation hostname" );100 System.exit( 1 );101 }102 103 // get user input day104 String day = ( String ) JOptionPane.showInputDialog( 105 null, "Select Day", "Day Selection", 106 JOptionPane.QUESTION_MESSAGE, null, days, days[ 0 ] );107 108 // take Entry109 TakeOperation take = new TakeOperation( args[ 0 ] );110 take.TakeAnEntry( day );111 112 take.showOutput();113 114 } // end method main115 }

6. main

Program output

Get user input day

Page 28: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.9 Notify Operation

• Five parameters– An Entry– A Transaction– A listener

– A long value (lease time)

– A MarshalledObject

• Two exceptions– RemoteException– TransactionException

Page 29: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // EntryListener.java2 // This class defines the listener for the NotifyOperation3 // application.4 package com.deitel.advjhtp1.javaspace.notify;5 6 // Jini core packages7 import net.jini.core.event.*;8 9 // Java core packages10 import java.rmi.RemoteException;11 import java.rmi.server.UnicastRemoteObject;12 import java.io.Serializable;13 14 public class EntryListener implements RemoteEventListener {15 16 private RemoteEventListener eventListener;17 18 // EntryListener constructor19 public EntryListener( RemoteEventListener listener )20 {21 eventListener = listener;22 23 // export stub object24 try {25 UnicastRemoteObject.exportObject( this );26 }27 28 // handle exception exporting stub29 catch ( RemoteException remoteException ) {30 remoteException.printStackTrace();31 }32 }33

ClassEntryListener

1. Import packages

2. Constructor

Export stub object

Page 30: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

34 // receive notifications35 public void notify( RemoteEvent remoteEvent )36 throws UnknownEventException, RemoteException37 {38 // forward notifications to NotifyOperation application39 eventListener.notify( remoteEvent );40 }41 }

3. Forward notification

Forward notification

Page 31: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // Fig: NotifyOperation.java2 // This application receives a notification when a matching entry3 // is written to the JavaSpace.4 package com.deitel.advjhtp1.javaspace.notify;5 6 // Jini core packages7 import net.jini.core.transaction.TransactionException;8 import net.jini.core.lease.Lease;9 import net.jini.core.event.*;10 11 // Jini extension package12 import net.jini.space.JavaSpace;13 14 // Java core packages15 import java.rmi.*;16 17 // Java standard extensions18 import javax.swing.*;19 20 // Deitel packages21 import com.deitel.advjhtp1.javaspace.common.*;22 23 public class NotifyOperation implements RemoteEventListener24 {25 private JavaSpace space;26 private static final String[] days = { "Monday", "Tuesday",27 "Wednesday", "Thursday", "Friday" };28 29 // constructor gets JavaSpace30 public NotifyOperation( String hostname ) 31 {32 // get JavaSpace33 String jiniURL = "jini://" + hostname;34 JavaSpaceFinder findtool = new JavaSpaceFinder( jiniURL );35 space = findtool.getJavaSpace();36 }

Class NotifyOperation

1. Import packages

2. Declarations

3. Constructor

Get JavaSpaces service

Page 32: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline37 38 // call notify method of JavaSpace39 public void notifyEntry( String day )40 {41 // get Entry listener42 EntryListener listener = new EntryListener( this );43 44 // specify matching template, asks JavaSpace to45 // send notification when matching entry is written46 // to JavaSpace47 try { 48 AttendeeCounter counter = new AttendeeCounter( day );49 50 MarshalledObject handback = new MarshalledObject( 51 "JavaSpace Notification" );52 space.notify( 53 counter, null, listener, 10 * 60 * 1000, handback );54 }55 56 // handle exception notifying space57 catch ( Exception exception ) {58 exception.printStackTrace();59 }60 61 } // end method notifyEntry62 63 // show output64 public void showOutput( String output )65 {66 JTextArea outputArea = new JTextArea();67 outputArea.setText( output );68 JOptionPane.showMessageDialog( null, outputArea, 69 "NotifyOperation Output", 70 JOptionPane.INFORMATION_MESSAGE );71 }

4. Notify Operation

4.1 specify template

4.2 specify handback object

4.3 notify

5. Show output

Hand back object

Notify operation

Display output to a message dialog

Page 33: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

73 // receive notifications74 public void notify( RemoteEvent remoteEvent )75 {76 String output = "\n";77 78 // prepare output79 try {80 output += "id: " + remoteEvent.getID() + "\n";81 output += "sequence number: " 82 + remoteEvent.getSequenceNumber() + "\n";83 String handback = ( String ) 84 remoteEvent.getRegistrationObject().get();85 output += "handback: " + handback + "\n";86 87 // display output88 showOutput( output );89 }90 91 // handle exception getting handback92 catch ( Exception exception ) {93 exception.printStackTrace();94 }95 }96

6. Receive notification

6.1 append output

Get event id

Get event sequence number

Get hand back object

Page 34: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline97 // method main98 public static void main( String args[] )99 {100 // get hostname101 if ( args.length != 1 ) {102 System.out.println( 103 "Usage: NotifyOperation hostname" );104 System.exit( 1 );105 }106 107 // get user input day108 String day = ( String ) JOptionPane.showInputDialog( 109 null, "Select Day", "Day Selection", 110 JOptionPane.QUESTION_MESSAGE, null, days, days[ 0 ] );111 112 // notify Entry113 NotifyOperation notifyOperation = 114 new NotifyOperation( args[ 0 ] );115 116 notifyOperation.notifyEntry( day );117 118 } // end method main119 }

7. main

Program output

Get user input day from an input dialog

Page 35: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.10 Method Snapshot

• Advantages– Optimize interactions with the JavaSpace

– Avoid repeated serialization process

• Restrictions– Snapshot Entry only valid in the JavaSpace that generated it

• Returns a specialized representation of the Entry

Page 36: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

1 // SnapshotUsage.java2 // This application removes entries from the JavaSpace using3 // method snapshot.4 package com.deitel.advjhtp1.javaspace.snapshot;5 6 // Jini core packages7 import net.jini.core.transaction.TransactionException;8 import net.jini.core.entry.UnusableEntryException;9 import net.jini.core.entry.Entry;10 11 // Jini extension package12 import net.jini.space.JavaSpace;13 14 // Java core packages15 import java.rmi.RemoteException;16 17 // Java extension package18 import javax.swing.*;19 20 // Deitel packages21 import com.deitel.advjhtp1.javaspace.common.*;22 23 public class SnapshotUsage {24 25 private JavaSpace space;26 private static final String[] days = { "Monday", "Tuesday",27 "Wednesday", "Thursday", "Friday" };28 private String output = "\n";29

Class SnapshotUsage

1. Import packages

2. Declarations

Page 37: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline30 // constructor gets JavaSpace31 public SnapshotUsage( String hostname )32 {33 // get JavaSpace34 String jiniURL = "jini://" + hostname;35 JavaSpaceFinder findtool = new JavaSpaceFinder( jiniURL );36 space = findtool.getJavaSpace();37 }38 39 // create snapshot entry object, pass this object as 40 // Entry parameter to take method41 public void snapshotEntry( String day )42 {43 // specify matching template, snapshot template44 // and remove matching entries from JavaSpace using 45 // snapshot entry46 try { 47 AttendeeCounter counter = new AttendeeCounter( day );48 Entry snapshotentry = space.snapshot( counter );49 AttendeeCounter resultCounter = ( AttendeeCounter ) 50 space.take( snapshotentry, null, JavaSpace.NO_WAIT );51 52 // keep removing entries until no more entry exists53 // in space54 while ( resultCounter != null ) {55 output += "Removing an entry ... \n";56 resultCounter = ( AttendeeCounter ) space.take( 57 snapshotentry, null, JavaSpace.NO_WAIT );58 }59 60 output += "No more entry to remove!\n";61 }62

3. Constructor

4. Snapshot

4.1 specify template

4.2 snapshot Entry

4.3 remove Entry

Snapshot Entry

Remove Entry from the JavaSpaces service

Keep removing until no more Entry exists in space

Get JavaSpaces service

Page 38: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline63 // handle exception network failure 64 catch ( RemoteException remoteException ) {65 remoteException.printStackTrace();66 }67 68 // handle exception invalid transaction69 catch ( TransactionException transactionException ) {70 transactionException.printStackTrace();71 }72 73 // handle exception unusable entry74 catch ( UnusableEntryException unusableEntryException ) {75 unusableEntryException.printStackTrace();76 } 77 78 // handle exception interrupt79 catch ( InterruptedException interruptedException ) {80 interruptedException.printStackTrace();81 }82 83 } // end method snapshotEntry84 85 // show output86 public void showOutput()87 {88 JTextArea outputArea = new JTextArea();89 outputArea.setText( output );90 JOptionPane.showMessageDialog( null, outputArea, 91 "SnapshotUsage Output", 92 JOptionPane.INFORMATION_MESSAGE );93 94 // terminate program95 System.exit( 0 );96 }97

4.5 catch exceptions

5. Show output

Display output to a message dialog

Page 39: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline98 // method main99 public static void main( String args[] )100 {101 // get hostname102 if ( args.length != 1 ) {103 System.out.println( 104 "Usage: SnapshotUsage hostname" );105 System.exit( 1 );106 }107 108 // get user input day109 String day = ( String ) JOptionPane.showInputDialog(110 null, "Select Day", "Day Selection",111 JOptionPane.QUESTION_MESSAGE, null, days, days[ 0 ] );112 113 // snapshot Entry114 SnapshotUsage snapshot = new SnapshotUsage( args[ 0 ] );115 snapshot.snapshotEntry( day );116 117 snapshot.showOutput();118 119 } // end method main120 }

6. main

Program output

Get user input day from an input dialog

Page 40: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.11 Updating Entry with Jini Transaction Service

• Update Entry– Take the Entry from the JavaSpace

– Change the values of the Entry fields

– Reinsert the Entry back into the JavaSpace

• All these steps are involved in a transaction

Page 41: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.11.1 Defining the User Interface

• UpdateInputWindow GUI– Day to update

– Number of people who will attend the seminar on that day

Page 42: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // UpdateInputWindow.java2 // This application is an user interface used3 // to get the input data.4 package com.deitel.advjhtp1.javaspace.update;5 6 // Java extension package7 import javax.swing.*;8 9 // Java core packages10 import java.awt.*;11 import java.awt.event.*;12 13 public class UpdateInputWindow extends JFrame {14 15 private String[] dates = { "Monday", "Tuesday",16 "Wednesday", "Thursday", "Friday" };17 private JButton okButton;18 private JComboBox dateComboBox;19 private JLabel firstLabel;20 private JTextField numberText;21 private String date = "Monday";22 private int count = 0;23 private String hostname;24 25 public UpdateInputWindow( String name )26 {27 super( "UpdateInputWindow" );28 Container container = getContentPane();29 30 hostname = name;31 32 // define center panel33 JPanel centerPanel = new JPanel();34 centerPanel.setLayout( new GridLayout( 2, 2, 0, 5 ) );35

ClassUpdateInputWindow

1. Import packages

2. Declarations

3. constructor

Constructor takes hostname as input argument

Page 43: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline36 // add label37 firstLabel = new JLabel( "Please choose a date:", 38 SwingConstants.CENTER );39 centerPanel.add( firstLabel );40 41 // add combo box42 dateComboBox = new JComboBox( dates );43 dateComboBox.setSelectedIndex( 0 );44 centerPanel.add( dateComboBox );45 46 // install listener to combo box47 dateComboBox.addItemListener( 48 49 new ItemListener() {50 51 public void itemStateChanged( ItemEvent itemEvent )52 {53 date = ( String )dateComboBox.getSelectedItem();54 }55 }56 );57 58 // add label59 JLabel numberLabel = new JLabel( 60 "Please specify a number:", SwingConstants.CENTER );61 centerPanel.add( numberLabel );62 63 // add text field64 numberText = new JTextField( 10 );65 centerPanel.add( numberText );66

3. constructor

Get user specified day

Page 44: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline67 // install listener to text field68 numberText.addActionListener( 69 70 new ActionListener() {71 72 public void actionPerformed( ActionEvent event ) 73 {74 count = Integer.parseInt( 75 event.getActionCommand() );76 }77 }78 );79 80 // define button panel 81 JPanel buttonPanel = new JPanel();82 buttonPanel.setLayout( new GridLayout( 1, 1, 0, 5 ) );83 84 // add OK button85 okButton = new JButton( "OK" );86 buttonPanel.add( okButton );87 88 // add listener to OK button89 okButton.addActionListener(90 91 new ActionListener() {92 93 public void actionPerformed( ActionEvent event ) 94 {95 // get user input96 count = Integer.parseInt( numberText.getText() );97

3. constructor

Get user input number

Page 45: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline98 if ( count == 0) {99 System.out.println(100 "Please Specify a Number" );101 }102 103 else { 104 UpdateOperation update = new UpdateOperation();105 String jiniURL = "jini://" + hostname;106 update.getServices( jiniURL );107 update.updateEntry( date, count );108 109 setVisible( false );110 update.showOutput();111 }112 }113 }114 );115 116 // put everything together117 container.add( centerPanel, BorderLayout.CENTER );118 container.add( buttonPanel, BorderLayout.SOUTH );119 120 // set window size and display it121 setSize( 320, 130 );122 setVisible( true );123 124 } // end updateInputWindow constructor125 }

3. Constructor

Get UpdateOperation class and update the Entry

Page 46: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

1 // TransactionManagerFinder.java2 // This application unicast discovers the 3 // TransactionManager service.4 package com.deitel.advjhtp1.javaspace.common;5 6 // Jini core packages7 import net.jini.core.discovery.LookupLocator;8 import net.jini.core.lookup.*;9 import net.jini.core.entry.Entry;10 import net.jini.core.transaction.server.TransactionManager;11 12 // Java core packages13 import java.io.*;14 import java.rmi.RMISecurityManager;15 import java.net.*;16 17 // Java extension package18 import javax.swing.*;19 20 public class TransactionManagerFinder {21 22 private TransactionManager transactionManager = null;23 24 public TransactionManagerFinder( String jiniURL )25 {26 LookupLocator locator = null;27 ServiceRegistrar registrar = null;28 29 System.setSecurityManager( new RMISecurityManager() );30

ClassTransactionManager

Finder

1. Import packages

2. Constructor

2.1 set security manager

Set security manager

Page 47: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline31 // get lookup service locator at "jini://hostname" 32 // use default port33 try {34 locator = new LookupLocator( jiniURL );35 36 // get registrar for the locator37 registrar = locator.getRegistrar();38 39 // specify service requirement40 Class[] types = new Class[] { 41 TransactionManager.class };42 ServiceTemplate template = 43 new ServiceTemplate( null, types, null );44 45 // find service 46 transactionManager = 47 (TransactionManager) registrar.lookup( template );48 } 49 50 // handle exception invalid jini URL51 catch ( MalformedURLException malformedURLException ) {52 malformedURLException.printStackTrace();53 }54 55 // handle exception I/O56 catch ( IOException ioException ) {57 ioException.printStackTrace();58 }59 60 // handle exception finding class61 catch ( ClassNotFoundException classNotFoundException ) {62 classNotFoundException.printStackTrace();63 }64

2.2 get lookup service

2.3 find Transaction service

2.4 catch exceptions

Find Transaction service

Specify matching template

Get lookup service registrar at “jini://hostname”

Page 48: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

65 // does not find any matching service66 if ( transactionManager == null ) {67 System.out.println( "No matching service" );68 }69 70 } // end TransactionManagerFinder constructor71 72 public TransactionManager getTransactionManager()73 {74 return transactionManager;75 }76 }

3 return TransactionManager

ClassOkButtonListener

1. Declarations

Return the TransactionManager service

Page 49: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // UpdateOperation.java2 // This application removes an Entry from the JavaSpace,3 // changes the variable's value in the returned Entry and4 // deposits the updated Entry into the JavaSpace. All these5 // operations are occurred within a transaction.6 package com.deitel.advjhtp1.javaspace.update;7 8 // Jini core package9 import net.jini.core.lease.Lease;10 import net.jini.core.transaction.*;11 import net.jini.core.entry.UnusableEntryException;12 import net.jini.core.transaction.server.TransactionManager;13 14 // Jini extension package15 import net.jini.space.JavaSpace;16 import net.jini.lease.*;17 18 // Java core packages19 import java.rmi.RemoteException;20 21 // Java extension packages22 import javax.swing.*;23 24 // Deitel packages25 import com.deitel.advjhtp1.javaspace.common.*;26 27 public class UpdateOperation implements OkButtonListener {28 29 private JavaSpace space;30 private TransactionManager transactionManager;31 private static String hostname = "";32 private static String day = "";33 private static int inputCount = 0;34 private static String output = "\n";35 36 // default constructor37 public UpdateOperation() {}

ClassUpdateOperation

1. Import packages

2. Declarations

3. Constructor

Page 50: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline38 39 // constructor gets JavaSpace and TransactionManager40 public void getServices( String jiniURL )41 {42 // get JavaSpace and TransactionManager43 JavaSpaceFinder findtool = 44 new JavaSpaceFinder( jiniURL );45 space = findtool.getJavaSpace();46 TransactionManagerFinder findTransaction = 47 new TransactionManagerFinder( jiniURL );48 transactionManager = 49 findTransaction.getTransactionManager();50 }51 52 // update Entry53 public void updateEntry( String inputDay, int countNumber )54 {55 day = inputDay;56 inputCount = countNumber;57 58 AttendeeCounter resultCounter = null;59 Transaction.Created transactionCreated = null;60 LeaseRenewalManager manager = new LeaseRenewalManager();61 62 int oldCount = 0;63 int newCount = 0;64 65 // create transaction and renew transaction's lease66 try {67 transactionCreated = TransactionFactory.create(68 transactionManager, Lease.FOREVER );69 manager.renewUntil( 70 transactionCreated.lease, Lease.FOREVER, null );71 }72

4. Get JavaSpace and TransactionMaager

5. Update Entry

5.1 create transaction

5.2 renew transaction’s lease

Create transaction

Renew the lease

Obtain JavaSpaces service

Obtain TransactionManager service

Page 51: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline73 // handle exception creating transaction and renewing lease74 catch ( Exception exception ) {75 exception.printStackTrace();76 }77 78 // specify matching template, remove template 79 // from JavaSpace in transaction, change 80 // variable's value and write updated template back 81 // to JavaSpace within a transaction82 try {83 84 // take Entry away from JavaSpace85 AttendeeCounter count = new AttendeeCounter( day );86 resultCounter = ( AttendeeCounter ) space.take( count,87 transactionCreated.transaction, JavaSpace.NO_WAIT );88 89 // if no matching entry90 if ( resultCounter == null ) {91 92 // set output message93 output += " No matching Entry is available!\n";94 }95 else { // if find a matching entry96 97 // update value98 oldCount = resultCounter.counter.intValue();99 newCount = oldCount + inputCount;100 101 // put updated Entry back to JavaSpace102 resultCounter.counter = new Integer( newCount );103 space.write( resultCounter, 104 transactionCreated.transaction, Lease.FOREVER );105

5.3 take Entry

5.4 update Entry

5.5 reinsert Entry

5.6 append output

Take Entry

Update EntryReinsert Entry

Page 52: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline106 // output result if transaction completes107 output += "Count Information:\n";108 output += " Day: ";109 output += resultCounter.day + "\n";110 output += " Old Count: " + oldCount + "\n";111 output += " New Count: " + newCount + "\n";112 }113 114 // commit transaction and release lease115 transactionCreated.transaction.commit();116 manager.remove( transactionCreated.lease );117 118 } // end try119 120 // handle exception updating Entry121 catch ( Exception exception ) {122 exception.printStackTrace();123 124 // revert change and release lease125 try {126 transactionCreated.transaction.abort();127 manager.remove( transactionCreated.lease );128 }129 130 // handle exception reverting change131 catch ( Exception abortException ) {132 abortException.printStackTrace();133 }134 }135 136 } // end method updateEntry137

5.7 commit transaction

5.8 catch exceptions

Commit transaction and release lease

Page 53: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

138 // show output139 public void showOutput()140 {141 JTextArea outputArea = new JTextArea();142 outputArea.setText( output );143 JOptionPane.showMessageDialog( null, outputArea, 144 "UpdateOperation Output", 145 JOptionPane.INFORMATION_MESSAGE );146 147 // terminate program148 System.exit( 0 );149 }150 151 public static void main( String args[])152 {153 // get hostname154 if ( args.length != 1 ) {155 System.out.println( 156 "Usage: UpdateOperation hostname" );157 System.exit( 1 );158 }159 else 160 hostname = args[ 0 ];161 162 // get user input day163 UpdateInputWindow input = new UpdateInputWindow( hostname );164 165 } // end method main166 }

6. continue process

7. Show output

Display output to a message dialog

Page 54: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

Program output

Page 55: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.12 Case Study: Distributed Image Processing

• JavaSpace-based distributed application– Partition large image into smaller pieces

– Run multiple image processors in parallel

– Each image processor process the smaller images

– Take processed subimages and build the complete processed image

Page 56: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.12.1 Defining an Image Processor

• Image processor node– Retrieve Entrys from a JavaSpaces Service

– Process the Entry– Write processed Entry back to the JavaSpaces Service

• Four filters– Blur

– Color

– Invert

– Sharpen

Page 57: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // Fig. 23.20 ImageEntry.java2 // This class defines the Entry for the image.3 package com.deitel.advjhtp1.javaspace.ImageProcessor;4 5 // Java core packages6 import java.util.*;7 8 // Java standard extension9 import javax.swing.ImageIcon;10 11 // Jini core packages12 import net.jini.core.entry.Entry;13 14 public class ImageEntry implements Entry {15 16 public String name;17 public String filter;18 public Integer number;19 public Boolean processed;20 public ImageIcon imageIcon;21 22 // empty constructor23 public ImageEntry() {}24 25 // ImageEntry constructor26 public ImageEntry( String imageName, String imageFilter, 27 int order, boolean done, ImageIcon icon )28 {29 name = imageName;30 filter = imageFilter;31 number = new Integer( order );32 processed = new Boolean( done );33 imageIcon = icon;34 }35

ClassImageEntry

1. Declarations

2. Constructors

Empty constructor

More constructors

Page 58: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

36 // ImageEntry constructor37 public ImageEntry( String imageName, boolean done )38 {39 name = imageName;40 processed = new Boolean( done );41 }42 43 // ImageEntry constructor44 public ImageEntry( String imageName )45 {46 name = imageName;47 }48 }

2. Constructors

More constructors

Page 59: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // Fig. 23.21 ImageProcessor.java2 // Takes entries from the JavaSpace, applies a filter to 3 // the image piece, and writes processed entry back to JavaSpace.4 package com.deitel.advjhtp1.javaspace.ImageProcessor;5 6 // Java standard extensions7 import javax.swing.*;8 9 // Jini core packages10 import net.jini.core.lease.Lease;11 import net.jini.core.transaction.*;12 import net.jini.core.transaction.server.TransactionManager;13 import net.jini.core.entry.*;14 import net.jini.core.transaction.*;15 import net.jini.lease.*;16 17 // Jini extension package18 import net.jini.space.JavaSpace;19 20 // Deitel packages21 import com.deitel.advjhtp1.javaspace.common.*;22 23 public class ImageProcessor {24 25 private JavaSpace space;26 private TransactionManager manager;27 28 // ImageProcessor constructor29 public ImageProcessor ( String hostname )30 {31 // get the JavaSpace32 String jiniURL = "jini://" + hostname;33 JavaSpaceFinder finder = 34 new JavaSpaceFinder( jiniURL );35 space = finder.getJavaSpace();

ClassImageProcessor

1. Import packages

2. Declarations

3. Constructor

3.1 get JavaSpaces service

Get JavaSpaces Service

Page 60: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline36 37 // get the TransactionManager38 TransactionManagerFinder findTransaction = 39 new TransactionManagerFinder( jiniURL );40 manager = 41 findTransaction.getTransactionManager();42 }43 44 // wait for unprocessed image45 public void waitForImage()46 {47 LeaseRenewalManager leaseManager = 48 new LeaseRenewalManager();49 50 while ( true ) {51 52 // get unprocessed image and process it 53 try {54 Transaction.Created transactionCreated = 55 TransactionFactory.create( 56 manager, Lease.FOREVER );57 58 // renew transaction's lease59 leaseManager.renewUntil( 60 transactionCreated.lease, Lease.FOREVER, null );61 62 ImageEntry template = new ImageEntry( null, false );63 ImageEntry entry = ( ImageEntry ) space.take( 64 template, transactionCreated.transaction, 65 Lease.FOREVER );66

3.2 get TransactionManager

4. Wait for unprocessed images

4.1 create transaction

4.2 renew transaction’s lease

4.3 specify ImageEntry template

4.4 remove the unprocessed image from the JavaSpaces service

Get transaction manager

Create transaction

Renew transaction’s lease

Specify templateRemove unprocessed image from JavaSpaces service

Page 61: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline67 if ( entry != null ) {68 69 // get image icon70 ImageIcon imageIcon = entry.imageIcon;71 72 Filters filters = new Filters( imageIcon );73 74 if ( entry.filter.equals( "BLUR" ) )75 filters.blurImage();76 77 else if ( entry.filter.equals( "COLOR" ) )78 filters.colorFilter();79 80 else if ( entry.filter.equals( "INVERT" ) )81 filters.invertImage();82 83 else if ( entry.filter.equals( "SHARP" ) )84 filters.sharpenImage();85 86 // update the fields of result entry87 entry.imageIcon = filters.getImageIcon();88 entry.processed = new Boolean( true );89 90 // put the updated Entry back to JavaSpace91 Lease writeLease = space.write( entry, 92 transactionCreated.transaction, 93 Lease.FOREVER );94 leaseManager.renewUntil( 95 writeLease, Lease.FOREVER, null );96 97 } // end if98

4.5 process the image if gets one from the JavaSpaces service

4.6 update Entry

4.7 put processed image back to the JavaSpaces service

Blur image

Color image

Invert image

Sharpen image

Update Entry

Put processed image back to the JavaSpaces service

Page 62: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

4.8 commit the transaction and release the lease

5. main

99 // commit the transaction and release the lease100 transactionCreated.transaction.commit();101 leaseManager.remove( transactionCreated.lease );102 103 } // end try104 105 // handle exception106 catch ( Exception exception ) {107 exception.printStackTrace();108 }109 110 } // end while111 112 } // end method wait for images113 114 public static void main( String[] args )115 {116 // get the hostname117 if ( args.length != 1 ) {118 System.out.println( 119 "Usage: ImageProcessor hostname" );120 System.exit( 1 );121 }122 123 ImageProcessor processor = 124 new ImageProcessor( args[ 0 ] );125 126 // wait for image127 processor.waitForImage();128 129 } // end method main130 }

Commit the transaction and release the lease

Page 63: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

1 // Fig. 23.24: Filters.java2 // This class filters an image.3 package com.deitel.advjhtp1.javaspace.ImageProcessor;4 5 // Java core packages6 import java.awt.*;7 import java.awt.image.*;8 9 // Java standard extensions10 import javax.swing.*;11 12 // Deitel packages13 import com.deitel.advjhtp1.java2d.*;14 15 public class Filters {16 17 Java2DImageFilter blurFilter;18 Java2DImageFilter sharpenFilter;19 Java2DImageFilter invertFilter;20 Java2DImageFilter colorFilter;21 22 BufferedImage bufferedImage;23

ClassFileters

1. Declarations

Page 64: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline24 // constructor method initializes ImageFilters and pulls25 // BufferedImage out of ImageIcon26 public Filters( ImageIcon icon ) 27 {28 blurFilter = new BlurFilter();29 sharpenFilter = new SharpenFilter();30 invertFilter = new InvertFilter();31 colorFilter = new ColorFilter();32 33 Image image = icon.getImage();34 bufferedImage = new BufferedImage( 35 image.getWidth( null ), image.getHeight( null ), 36 BufferedImage.TYPE_INT_RGB );37 38 Graphics2D gg = bufferedImage.createGraphics();39 gg.drawImage( image, null, null );40 }41 42 // apply BlurFilter to bufferedImage43 public void blurImage() 44 {45 bufferedImage = blurFilter.processImage( bufferedImage );46 }47 48 // apply SharpenFilter to bufferedImage49 public void sharpenImage()50 {51 bufferedImage = sharpenFilter.processImage( 52 bufferedImage );53 }54

2. Constructor

3. Blur processor

4. Sharpen processor

Get BufferedImage

Apply filters to image

Page 65: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

55 // apply InvertFilter to bufferedImage56 public void invertImage() 57 {58 bufferedImage = invertFilter.processImage( 59 bufferedImage );60 }61 62 // apply ColorFilter to bufferedImage63 public void colorFilter()64 {65 bufferedImage = colorFilter.processImage( 66 bufferedImage );67 }68 69 // constructs and returns an ImageIcon from bufferedImage70 public ImageIcon getImageIcon()71 {72 return ( new ImageIcon( bufferedImage ) );73 }74 }

5. Invert processor

6. Color processor

7. Return image

Apply filters to image

Page 66: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.12.2 Partitioning an Image into Smaller Pieces

• Concurrently filter the smaller images

Page 67: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

ClassImageProcessingClient

1. Import packages

2. Declarations

1 // Fig. 23.23 ImageProcessingClient.java2 // The application asks for user-specified image file, image 3 // filter type and image partition number, filters the image4 // and displays the processed image.5 package com.deitel.advjhtp1.javaspace.ImageProcessor;6 7 // Java core packages8 import java.awt.*;9 import java.awt.event.*;10 import java.util.*;11 import java.io.*;12 13 // Java extension packages14 import javax.swing.*;15 16 // Jini core packages17 import net.jini.core.lease.Lease;18 import net.jini.core.entry.*;19 import net.jini.core.transaction.*;20 import net.jini.core.transaction.server.TransactionManager;21 22 // Jini extension packages23 import net.jini.space.JavaSpace;24 25 // Deitel packages26 import com.deitel.advjhtp1.javaspace.common.*;27 28 public class ImageProcessingClient extends JFrame {29 30 private String[] operations = { "BLUR", "COLOR",31 "INVERT", "SHARP" };32 private JButton okButton;33 private JComboBox operationComboBox;34 private JTextField imageText;35 private JTextField numberText;

Page 68: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

3. Constructor

3.1 get image

36 37 private static String hostname = "";38 private String imageName;39 private String operation = "BLUR";40 private int partitionNumber = 0;41 42 public ImageProcessingClient( String host )43 {44 super ( "ImageProcessInput" );45 46 hostname = host;47 Container container = getContentPane();48 49 // define the center panel50 JPanel centerPanel = new JPanel();51 centerPanel.setLayout( new GridLayout( 3, 2, 0, 5 ) );52 53 // add image label54 JLabel imageLabel = new JLabel( "Image File:", 55 SwingConstants.CENTER );56 centerPanel.add( imageLabel );57 58 JButton openFile = new JButton( 59 "Choose file to process" );60 openFile.addActionListener( 61 62 new ActionListener() {63 64 public void actionPerformed( ActionEvent event )65 {66 JFileChooser fileChooser = new JFileChooser();67 68 fileChooser.setFileSelectionMode( 69 JFileChooser.FILES_ONLY );70 int result = fileChooser.showOpenDialog( null );71 File file;

Get image name from JFileChooser

Page 69: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

3.2 get partition number

72 73 // user clicked Cancel button on dialog74 if ( result == JFileChooser.CANCEL_OPTION )75 file = null;76 else {77 file = fileChooser.getSelectedFile();78 imageName = file.getPath();79 }80 81 } // end method actionPerformed82 83 } // end ActionListener constructor84 85 ); // end addActionListener86 87 centerPanel.add( openFile );88 89 // add number label90 JLabel numberLabel = new JLabel( "Partition Number:", 91 SwingConstants.CENTER );92 centerPanel.add( numberLabel );93 94 // add number text field95 numberText = new JTextField( 10 );96 centerPanel.add( numberText );97 98 // install a listener to the number text field99 numberText.addActionListener( 100 101 new ActionListener() {102

Partition number field

Get image name in full path

Page 70: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

3.3 get filter type

103 // get the text when the user feeds a return 104 // character in the text field105 public void actionPerformed( ActionEvent event ) 106 {107 partitionNumber = Integer.parseInt(108 event.getActionCommand() );109 }110 }111 );112 113 // add operation label114 JLabel operationLabel = new JLabel( "Operation Type:", 115 SwingConstants.CENTER );116 centerPanel.add( operationLabel );117 118 // add a combo box119 operationComboBox = new JComboBox( operations );120 operationComboBox.setSelectedIndex( 0 );121 centerPanel.add( operationComboBox );122 123 // install a listener to the combo box124 operationComboBox.addItemListener( 125 126 new ItemListener() {127 128 // an operation other than BLUR is selected129 public void itemStateChanged( ItemEvent itemEvent )130 {131 operation = 132 ( String ) operationComboBox.getSelectedItem();133 }134 }135 );136

Get filter type

Combo box to select filter type

Page 71: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

3.4 Ok button action

137 // define the button panel 138 JPanel buttonPanel = new JPanel();139 buttonPanel.setLayout( new GridLayout( 1, 1, 0, 5 ) );140 141 // add the OK button142 okButton = new JButton( "OK" );143 buttonPanel.add( okButton );144 145 // add a listener to the OK button146 okButton.addActionListener(147 148 new ActionListener() {149 150 // partition image file into number of pieces user 151 // specified152 public void actionPerformed( ActionEvent event ) 153 {154 // get user inputs155 partitionNumber = Integer.parseInt( 156 numberText.getText() );157 158 // check whether the user 159 // fills in both text fields160 if ( ( partitionNumber == 0 ) 161 || ( imageName == null ) ) {162 JOptionPane.showMessageDialog( null, 163 "Either image name or partition number " 164 + "is not specified!", "Error", 165 JOptionPane.ERROR_MESSAGE);166 }167

OK button action

Error message is displayed if the user does not supply image name or partition number

Page 72: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

4. Collect processed images

4.1 get JavaSpaces service

168 else {169 setVisible( false );170 171 // partition the image into smaller pieces 172 // and store the sub images into a JavaSpace173 ImageSeparator imageSeparator = 174 new ImageSeparator( 175 imageName, operation, partitionNumber );176 imageSeparator.partitionImage();177 imageSeparator.storeImage( hostname );178 imageSeparator.displayImage();179 collect();180 }181 182 } // end method actionPerformed183 184 } // end ActionListener constructor185 186 ); // end addActionListener187 188 // put everything together189 container.add( centerPanel, BorderLayout.CENTER );190 container.add( buttonPanel, BorderLayout.SOUTH );191 192 } // end ImageProcessingClient constructor193 194 // collect processed images195 public void collect()196 {197 // get the JavaSpace198 String jiniURL = "jini://" + hostname;199 JavaSpaceFinder findtool = 200 new JavaSpaceFinder( jiniURL );201 JavaSpace space = findtool.getJavaSpace();202

Get JavaSpaces service

Partition the image, store subimages into the JavaSpaces service and then collect the processed subimages

Page 73: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

4.2 get all processed images

203 Vector unOrderedImages = new Vector();204 Vector orderedImages = null;205 206 // removes all images in the JavaSpace 207 // that have the specified name208 try {209 double squareRoot = Math.sqrt( partitionNumber );210 211 if ( Math.floor( squareRoot ) != ( squareRoot ) ) 212 partitionNumber = 4; 213 214 // specify the matching template215 ImageEntry template = new ImageEntry( imageName, true );216 217 // snapshot the template218 Entry snapshotEntry = space.snapshot( template );219 220 // collect images221 for ( int i = 0; i < partitionNumber ; i++ ) {222 ImageEntry remove = ( ImageEntry ) space.take(223 snapshotEntry, null, Lease.FOREVER );224 unOrderedImages.add( remove );225 }226 227 int imageCount = unOrderedImages.size();228 orderedImages = 229 new Vector( imageCount );230 231 // initialize the Vector232 for ( int i = 0; i < imageCount; i++ )233 orderedImages.add( null );234

Specify matching template

Get all processed images

Default partition number is 4

Page 74: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

4.3 order collected images

4.4 build complete processed image

235 // order the sub images236 for ( int i = 0; i < imageCount; i++ ) {237 ImageEntry image = 238 ( ImageEntry ) unOrderedImages.elementAt( i );239 orderedImages.setElementAt( 240 image.imageIcon, image.number.intValue() );241 }242 243 } // end try244 245 // handle exception collecting images 246 catch ( Exception exception ) {247 exception.printStackTrace();248 } 249 250 // put images together and display the result image251 if ( orderedImages.size() > 0) {252 ImageParser imageParser = new ImageParser();253 254 ImageIcon icon = imageParser.putTogether( 255 orderedImages );256 257 ImageDisplayer imageDisplayer = 258 new ImageDisplayer( icon );259 260 imageDisplayer.setSize( icon.getIconWidth() + 50, 261 icon.getIconHeight() + 50 );262 imageDisplayer.setVisible( true );263 imageDisplayer.setDefaultCloseOperation( 264 JFrame.EXIT_ON_CLOSE );265 }266

Order collected images

Build complete processed image

Exit when closes window

Page 75: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

5. main267 else {268 JOptionPane.showMessageDialog( null, 269 "Invalid image name", "Error", 270 JOptionPane.ERROR_MESSAGE);271 272 // terminate program273 System.exit( 0 );274 }275 276 } // end method collect277 278 public static void main( String[] args )279 {280 // get the hostname281 if ( args.length != 1 ) {282 System.out.println( 283 "Usage: ImageProcessingClient hostname" );284 System.exit( 1 );285 }286 287 ImageProcessingClient processor = 288 new ImageProcessingClient( args[ 0 ] );289 290 // set the window size and display it291 processor.setSize( 350, 150 );292 processor.setVisible( true );293 294 } // end method main295 }

Page 76: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // Fig. 23.24 ImageSeparator.java2 // This class partitions the image into smaller pieces evenly3 // and stores the smaller images into a JavaSpace.4 package com.deitel.advjhtp1.javaspace.ImageProcessor;5 6 // Java core packages7 import java.util.*;8 import java.rmi.*;9 10 // Java standard extensions11 import javax.swing.*;12 13 // Jini core packages14 import net.jini.core.lease.Lease;15 import net.jini.core.transaction.TransactionException;16 17 // Jini extension packages18 import net.jini.space.JavaSpace;19 import net.jini.lease.*;20 21 // Deitel packages22 import com.deitel.advjhtp1.javaspace.common.*;23 24 public class ImageSeparator {25 26 private String imageName;27 private String filterType;28 private int partitionNumber;29 private Vector imagePieces;30 private ImageIcon icon;31 32 // ImageSeparator constructor33 public ImageSeparator( 34 String name, String type, int number )35 {36 imageName = name;

ClassImageSeparator

1. Import packages

2. Declarations

3. Constructor

Constructor takes image name, filter type and partition number

Page 77: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

4. Partition image

5. Display image

6. Write subimages into the JavaSpace

6.1 get JavaSpaces service

37 filterType = type;38 partitionNumber = number;39 }40 41 // partition the image into smaller pieces evenly42 public void partitionImage()43 {44 ImageParser imageParser = new ImageParser();45 icon = new ImageIcon( imageName );46 47 // partition the image48 imagePieces = imageParser.parseImage( 49 icon, partitionNumber );50 }51 52 // display the image53 public void displayImage( )54 {55 ImageDisplayer imageDisplayer = 56 new ImageDisplayer( icon );57 imageDisplayer.setSize( icon.getIconWidth() + 50, 58 icon.getIconHeight() + 50 );59 imageDisplayer.setVisible( true );60 }61 62 // write image pieces into a JavaSpace63 public void storeImage( String hostname )64 {65 // get the JavaSpace66 String jiniURL = "jini://" + hostname;67 JavaSpaceFinder findtool = 68 new JavaSpaceFinder( jiniURL );69 JavaSpace space = findtool.getJavaSpace();70 71 LeaseRenewalManager leaseManager = 72 new LeaseRenewalManager();

Partition image

Display image

Get JavaSpaces service

Page 78: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

6.2 put sumimages into JavaSpace

73 74 // write sub images to JavaSpace75 try {76 77 for ( int i = 0; i < imagePieces.size(); i++ ) {78 ImageIcon subImage = 79 ( ImageIcon ) imagePieces.elementAt( i );80 81 ImageEntry imageEntry = new ImageEntry( 82 imageName, filterType, i, false, subImage );83 84 Lease writeLease = space.write( 85 imageEntry, null, Lease.FOREVER );86 leaseManager.renewUntil( 87 writeLease, Lease.FOREVER, null );88 }89 }90 91 // if a network failure occurs92 catch ( RemoteException remoteException ) {93 remoteException.printStackTrace();94 }95 96 // if write operates under an invalid transaction97 catch ( TransactionException transactionException ) {98 transactionException.printStackTrace();99 }100 101 } // end method storeImage102 }

Put subimages into JavaSpace

Page 79: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // Fig. 23.27: ImageParser.java2 // This class partitions an image into smaller pieces.3 package com.deitel.advjhtp1.javaspace.ImageProcessor;4 5 // Java core packages6 import java.awt.image.*;7 import java.net.URL;8 import java.awt.*;9 import java.lang.*;10 import java.util.Vector;11 import java.awt.geom.*;12 13 // Java standard extensions14 import javax.swing.*;15 16 public class ImageParser {17 18 ImageIcon image; 19 20 public ImageParser() {}21 22 // pass parseImage an ImageIcon on the number of piece 23 // you want it split into the number of piece must be a 24 // perfect square - this can be extended later25 public Vector parseImage( 26 ImageIcon imageIcon, int numberPieces ) 27 {28 Vector vector = new Vector();29 double squareRoot = Math.sqrt( numberPieces );30 31 if ( Math.floor( squareRoot ) != ( squareRoot ) ) {32 System.out.println( "This is not a square number,"33 + " setting to default...");34 numberPieces = 4; 35 }

ClassImageParser

1. Import packages

2. Constructor

3. Partition image

Partition image to subimages

If not a square number, set to default which is 4

Page 80: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline36 37 // get number of rows and columns38 int numberRows = ( int ) Math.sqrt( numberPieces );39 int numberColumns = ( int ) Math.sqrt( numberPieces );40 41 // retrieve Image from BufferedImage42 Image image = imageIcon.getImage();43 BufferedImage bufferedImage = new BufferedImage(44 image.getWidth( null ), image.getHeight( null ), 45 BufferedImage.TYPE_INT_RGB );46 47 Graphics2D gg = bufferedImage.createGraphics();48 gg.drawImage( image, null, null );49 50 // get size of each piece51 int width = bufferedImage.getWidth() / numberColumns;52 int height = bufferedImage.getHeight() / numberRows;53 54 // make each of images55 for ( int x = 0; x < numberRows; x++ ) {56 57 for ( int y = 0; y < numberColumns; y++ ) {58 vector.add( new ImageIcon( 59 bufferedImage.getSubimage(60 x * width, y * height, width, height ) ) );61 }62 }63 64 return vector;65 66 } // end method parseImage67

3. Partition image

Retrieve image from buffered image

Get subimages

Page 81: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

68 // takes a vector of image icons (must be a square number)69 // of elements and returns an image icon with the images 70 // put back together again 71 public ImageIcon putTogether( Vector vector )72 {73 double size = vector.size();74 int numberRowColumn = ( int ) Math.sqrt( size );75 76 // step 1, get first Image77 Image tempImage = 78 ( ( ImageIcon ) vector.get( 0 ) ).getImage();79 80 // get total size of one piece81 int width = tempImage.getWidth( null );82 int height = tempImage.getHeight( null );83 84 // create buffered image85 BufferedImage totalPicture = new BufferedImage( 86 width * numberRowColumn, height * numberRowColumn, 87 BufferedImage.TYPE_INT_RGB );88 89 // create Graphics for BufferedImage90 Graphics2D graphics = totalPicture.createGraphics();91

4. Reform image

Build completed processed image

Page 82: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

92 // draw images from the vector into buffered image93 for ( int x = 0; x < numberRowColumn; x++ ) {94 95 for ( int y = 0; y < numberRowColumn; y++ ) {96 Image image = ( ( ImageIcon ) vector.get( 97 y + numberRowColumn * x ) ).getImage();98 graphics.drawImage( image, 99 AffineTransform.getTranslateInstance( 100 x * width, y * height ), null );101 }102 }103 104 return new ImageIcon( totalPicture );105 106 } // end method putTogether107 }

4. Reform image

Page 83: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline1 // Fig. 23.28: ImageDisplayer.java2 // This application is an user interface used3 // to display an image.4 package com.deitel.advjhtp1.javaspace.ImageProcessor;5 6 // Java extension packages7 import javax.swing.*;8 9 // Java core packages10 import java.awt.*;11 import java.awt.event.*;12 13 public class ImageDisplayer extends JFrame {14 15 public ImageDisplayer( ImageIcon icon)16 {17 super( "ImageDisplay" );18 Container container = getContentPane();19 20 // define the center panel21 JPanel centerPanel = new JPanel();22 23 // add display label24 JLabel imageLabel = new JLabel( 25 icon, SwingConstants.LEFT );26 centerPanel.add( imageLabel );27 28 container.add( centerPanel, BorderLayout.CENTER );29 30 } // end ImageDisplayer constructor31 }

ClassImageDisplayer

1. Constructor

1.1 GUI

Page 84: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.12.3 Compiling and Running the Example

• Services needed to execute the example– Web server

– RMI activation daemon

– Jini lookup service

– JavaSpaces service

– Jini Transaction service

• Running ImageProcessors and clients on different machines

Page 85: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc.All rights reserved.

Outline

Program output

Page 86: 2001 Prentice Hall, Inc. All rights reserved. Chapter 23 - JavaSpaces Outline 23.1 Introduction 23.2 JavaSpaces Service Properties 23.3 JavaSpaces Service

2001 Prentice Hall, Inc. All rights reserved.

23.13 Internet and World Wide Web Resources

• www.sun.com/jini/specs/js1_1.pdf

• www.javaworld.com/jw-11-1999/jw-11-jiniology.html

• www.javaworld.com/jw-01-2000/jw-01-jiniology.html

• www.javaworld.com/jw-03-2000/jw-03-jiniology.html • www.javaworld.com/jw-04-2000/jw-0421-jiniology.html

• www.javaworld.com/jw-06-2000/jw-0623-jiniology.html• www.byte.com/documents/s=146/BYT19990921S0001/index.htm