Java Reference
In-Depth Information
participants, and an array of possible alternate dates for the appointment. The changeAppointment method
allows one of the AppointmentBook objects to communicate with the others using RMI, calling the changeDate
method on every one of the participants until all agree on an alternate date for the Appointment .
Example 4.30 AppointmentBook.java
1. import java.util.ArrayList;
2. import java.util.HashMap;
3. import java.util.Date;
4. import java.rmi.Naming;
5. import java.rmi.server.UnicastRemoteObject;
6. import java.rmi.RemoteException;
7. public class AppointmentBook implements AppointmentTransactionParticipant{
8. private static final String TRANSACTION_SERVICE_PREFIX = "transactionParticipant";
9. private static final String TRANSACTION_HOSTNAME = "localhost";
10. private static int index = 1;
11. private String serviceName = TRANSACTION_SERVICE_PREFIX + index++;
12. private HashMap appointments = new HashMap();
13. private long currentTransaction;
14. private Appointment currentAppointment;
15. private Date updateStartDate;
16.
17. public AppointmentBook(){
18. try {
19. UnicastRemoteObject.exportObject(this);
20. Naming.rebind(serviceName, this);
21. }
22. catch (Exception exc){
23. System.err.println("Error using RMI to register the AppointmentBook " + exc);
24. }
25. }
26.
27. public String getUrl(){
28. return "//" + TRANSACTION_HOSTNAME + "/" + serviceName;
29. }
30.
31. public void addAppointment(Appointment appointment){
32. if (!appointments.containsValue(appointment)){
33. if (!appointments.containsKey(appointment.getStartDate())){
34. appointments.put(appointment.getStartDate(), appointment);
35. }
36. }
37. }
38. public void removeAppointment(Appointment appointment){
39. if (appointments.containsValue(appointment)){
40. appointments.remove(appointment.getStartDate());
41. }
42. }
43.
44. public boolean join(long transactionID){
45. if (currentTransaction != 0){
46. return false;
47. } else {
48. currentTransaction = transactionID;
49. return true;
50. }
51. }
52. public void commit(long transactionID) throws TransactionException{
53. if (currentTransaction != transactionID){
54. throw new TransactionException("Invalid TransactionID");
55. } else {
56. removeAppointment(currentAppointment);
57. currentAppointment.setStartDate(updateStartDate);
58. appointments.put(updateStartDate, currentAppointment);
59. }
60. }
61. public void cancel(long transactionID){
62. if (currentTransaction == transactionID){
63. currentTransaction = 0;
64. appointments.remove(updateStartDate);
65. }
66. }
67. public boolean changeDate(long transactionID, Appointment appointment,
68. Date newStartDate) throws TransactionException{
69. if ((appointments.containsValue(appointment)) && (!appointments.
containsKey(newStartDate))){
70. appointments.put(newStartDate, null);
Search WWH ::




Custom Search