Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Applied Java™ Patterns - Stephen Stelting, Olav Maassen.pdf
Скачиваний:
202
Добавлен:
24.05.2014
Размер:
2.84 Mб
Скачать

111.

}

112.

}

113.

catch (TransactionException exc){

114.

return false;

115.

}

116.}

117.}

118.catch (RemoteException exc){

119.return false;

120.}

121.return true;

122.}

123.private void commitAll(long transactionID,

AppointmentTransactionParticipant[]participants)

124.throws TransactionException, RemoteException{

125.for (int i = 0; i < participants.length; i++){

126.participants[i].commit(transactionID);

127.}

128.}

129.private void cancelAll(long transactionID, AppointmentTransactionParticipant[]

participants)

130.throws RemoteException{

131.for (int i = 0; i < participants.length; i++){

132.participants[i].cancel(transactionID);

133.}

134.}

135.public String toString(){

136.return serviceName + " " + appointments.values().toString();

137.}

138.}

The TransactionException is a signal exception; it has no special content and gets thrown when an invalid transactionID is supplied to some methods. The receiver might report the exception or ignore it, depending on its processing needs.

Example A.256 TransactionException.java

1.public class TransactionException extends Exception{

2.public TransactionException(String msg){

3.super(msg);

4.}

5.}

Support classes for this example represent the appointment and its elements, Three interfaces— Appointment, Contact, and Location — define the core business behavior. The classes AppointmentImpl, ContactImpl, and LocationImpl provide implementation for the interface behavior.

Example A.257 Appointment.java

1.import java.util.ArrayList;

2.import java.util.Date;

3.import java.io.Serializable;

4.public interface Appointment extends Serializable{

5.public static final String EOL_STRING = System.getProperty("line.separator");

7.public Date getStartDate();

8.public String getDescription();

9.public ArrayList getAttendees();

10.public Location getLocation();

11.

12.public void setDescription(String newDescription);

13.public void setLocation(Location newLocation);

14.public void setStartDate(Date newStartDate);

15.public void setAttendees(ArrayList newAttendees);

16.public void addAttendee(Contact attendee);

17.public void removeAttendee(Contact attendee);

18.}

Example A.258 AppointmentImpl.java

1.import java.util.ArrayList;

2.import java.util.Date;

3.public class AppointmentImpl implements Appointment{

4.private Date startDate;

5.private String description;

6.private ArrayList attendees = new ArrayList();

7.private Location location;

362

8.

9.public AppointmentImpl(String newDescription, ArrayList newAttendees,

10.Location newLocation, Date newStartDate){

11.description = newDescription;

12.attendees = newAttendees;

13.location = newLocation;

14.startDate = newStartDate;

15.}

16.

17.public Date getStartDate(){ return startDate; }

18.public String getDescription(){ return description; }

19.public ArrayList getAttendees(){ return attendees; }

20.public Location getLocation(){ return location; }

21.

22.public void setDescription(String newDescription){ description = newDescription; }

23.public void setLocation(Location newLocation){ location = newLocation; }

24.public void setStartDate(Date newStartDate){ startDate = newStartDate; }

25.public void setAttendees(ArrayList newAttendees){

26.if (newAttendees != null){

27. attendees = newAttendees;

28.}

29.}

31.public void addAttendee(Contact attendee){

32.if (!attendees.contains(attendee)){

33. attendees.add(attendee);

34.}

35.}

37.public void removeAttendee(Contact attendee){

38.attendees.remove(attendee);

39.}

40.

41.public int hashCode(){

42.return description.hashCode() ^ startDate.hashCode();

43.}

44.

45.public boolean equals(Object object){

46.if (!(object instanceof AppointmentImpl)){

47.

return false;

48.}

49.if (object.hashCode() != hashCode()){

50.

return false;

51.}

52.return true;

53.}

54.

55.public String toString(){

56.return " Description: " + description + EOL_STRING +

57. " Start Date: " + startDate + EOL_STRING + 58. " Location: " + location + EOL_STRING + 59. " Attendees: " + attendees;

60.}

61.}

Example A.259 Contact.java

1.import java.io.Serializable;

2.public interface Contact extends Serializable{

3.public static final String SPACE = " ";

4.public String getFirstName();

5.public String getLastName();

6.public String getTitle();

7.public String getOrganization();

8.

9.public void setFirstName(String newFirstName);

10.public void setLastName(String newLastName);

11.public void setTitle(String newTitle);

12.public void setOrganization(String newOrganization);

13.}

Example A.260 ContactImpl.java

1.public class ContactImpl implements Contact{

2.private String firstName;

3.private String lastName;

4.private String title;

5.private String organization;

6.

363

7.public ContactImpl(){}

8.public ContactImpl(String newFirstName, String newLastName,

9.String newTitle, String newOrganization){

10. firstName = newFirstName;

11. lastName = newLastName;

12. title = newTitle;

13. organization = newOrganization;

14. }

15.

16.public String getFirstName(){ return firstName; }

17.public String getLastName(){ return lastName; }

18.public String getTitle(){ return title; }

19.public String getOrganization(){ return organization; }

21.public void setFirstName(String newFirstName){ firstName = newFirstName; }

22.public void setLastName(String newLastName){ lastName = newLastName; }

23.public void setTitle(String newTitle){ title = newTitle; }

24.public void setOrganization(String newOrganization){ organization = newOrganization; }

26.public String toString(){

27.return firstName + SPACE + lastName;

28.}

29.}

Example A.261 Location.java

1.import java.io.Serializable;

2.public interface Location extends Serializable{

3.public String getLocation();

4.public void setLocation(String newLocation);

5.}

Example A.262 LocationImpl.java

1.public class LocationImpl implements Location{

2.private String location;

3.

4.public LocationImpl(){ }

5.public LocationImpl(String newLocation){

6.location = newLocation;

7.}

8.

9. public String getLocation(){ return location; }

10.

11. public void setLocation(String newLocation){ location = newLocation; }

12.

13.public String toString(){ return location; }

14.}

RunPattern demonstrates coordination among the AddressBook objects to reschedule an appointment. It creates three AddressBooks, setting up conflict-ing appointments in two of them. Next, it instructs an AddressBook to update the appointment. This results in an appointment in the address books with the first start time available to all three AddressBooks: 12 noon.

Example A.263 RunPattern.java

1.import java.io.IOException;

2.import java.rmi.Naming;

3.import java.util.Date;

4.import java.util.Calendar;

5.import java.util.ArrayList;

6.public class RunPattern{

7.private static Calendar dateCreator = Calendar.getInstance();

9.public static void main(String [] arguments){

10.System.out.println("Example for the Transaction pattern");

11.System.out.println("This code example shows how a Transaction can");

12.System.out.println(" be applied to support change across a distributed");

13.System.out.println(" system. In ths case, a distributed transaction");

14.System.out.println(" is used to coordinate the change of dates in");

15.System.out.println(" appointment books.");

16.

17.System.out.println("Running the RMI compiler (rmic)");

18.System.out.println();

19.try{

20. Process p1 = Runtime.getRuntime().exec("rmic AppointmentBook");

21. p1.waitFor();

364

22.}

23.catch (IOException exc){

24. System.err.println("Unable to run rmic utility. Exiting application.");

25. System.exit(1);

26.}

27.catch (InterruptedException exc){

28.

System.err.println("Threading problems encountered while using the rmic utility.");

29.

}

30.

 

31.System.out.println("Starting the rmiregistry");

32.System.out.println();

33.try{

34. Process rmiProcess = Runtime.getRuntime().exec("rmiregistry");

35. Thread.sleep(15000);

36.}

37.catch (IOException exc){

38.System.err.println("Unable to start the rmiregistry. Exiting application.");

39. System.exit(1);

40.}

41.catch (InterruptedException exc){

42.System.err.println("Threading problems encountered when starting the rmiregistry.");

43.}

44.

45.System.out.println("Creating three appointment books");

46.System.out.println();

47.AppointmentBook apptBookOne = new AppointmentBook();

48.AppointmentBook apptBookTwo = new AppointmentBook();

49.AppointmentBook apptBookThree = new AppointmentBook();

51.System.out.println("Creating appointments");

52.System.out.println();

53.Appointment apptOne = new AppointmentImpl("Swim relay to Kalimantan (or Java)", new

ArrayList(),

54. new LocationImpl("Sidney, Australia"), createDate(2001, 11, 5, 11, 0));

55.Appointment apptTwo = new AppointmentImpl("Conference on World Patternization", new

ArrayList(),

56. new LocationImpl("London, England"), createDate(2001, 11, 5, 14, 0));

57.Appointment apptThree = new AppointmentImpl("Society for the Preservation of Java

-Annual Outing",

58. new ArrayList(), new LocationImpl("Kyzyl, Tuva"), createDate(2001, 11, 5, 10, 0));

59.

60.System.out.println("Adding appointments to the appointment books");

61.System.out.println();

62.apptBookOne.addAppointment(apptThree);

63.apptBookTwo.addAppointment(apptOne);

64.apptBookOne.addAppointment(apptTwo);

65.apptBookTwo.addAppointment(apptTwo);

66.apptBookThree.addAppointment(apptTwo);

67.

68.System.out.println("AppointmentBook contents:");

69.System.out.println();

70.System.out.println(apptBookOne);

71.System.out.println(apptBookTwo);

72.System.out.println(apptBookThree);

73.System.out.println();

74.

75.System.out.println("Rescheduling an appointment");

76.System.out.println();

77.System.out.println();

78.boolean result = apptBookThree.changeAppointment(apptTwo, getDates(2001, 11, 5, 10,

79.

3),

lookUpParticipants(new String[] { apptBookOne.getUrl(), apptBookTwo.getUrl(),

80.

apptBookThree.getUrl() }),

20000L);

81.

 

82.System.out.println("Result of rescheduling was " + result);

83.System.out.println("AppointmentBook contents:");

84.System.out.println();

85.System.out.println(apptBookOne);

86.System.out.println(apptBookTwo);

87.System.out.println(apptBookThree);

88.}

89.

90.private static AppointmentTransactionParticipant[] lookUpParticipants(String[]

remoteUrls){

91.AppointmentTransactionParticipant[] returnValues =

92. new AppointmentTransactionParticipant[remoteUrls.length];

365

93.for (int i = 0; i < remoteUrls.length; i++){

94.

try {

95.

returnValues[i] = (AppointmentTransactionParticipant)

96.

Naming.lookup(remoteUrls[i]);

}

97.

catch (Exception exc){

98.

System.out.println("Error using RMI to look up a transaction participant");

99.

}

100.}

101.return returnValues;

102.}

103.

104.private static Date[] getDates(int year, int month, int day, int hour, int increment){

105.Date[] returnDates = new Date[increment];

106.for (int i = 0; i < increment; i++){

107.returnDates[i] = createDate(year, month, day, hour + i, 0);

108.}

109.return returnDates;

110.}

111.

112.public static Date createDate(int year, int month, int day, int hour, int minute){

113.dateCreator.set(year, month, day, hour, minute);

114.return dateCreator.getTime();

115.}

116.}

366