View Javadoc

1   package se.citerus.dddsample.domain.model.handling;
2   
3   import org.apache.commons.lang.Validate;
4   import se.citerus.dddsample.domain.shared.ValueObject;
5   
6   import java.util.*;
7   import static java.util.Collections.sort;
8   
9   /**
10   * The handling history of a cargo.
11   *
12   */
13  public class HandlingHistory implements ValueObject<HandlingHistory> {
14  
15    private final List<HandlingEvent> handlingEvents;
16  
17    public static final HandlingHistory EMPTY = new HandlingHistory(Collections.<HandlingEvent>emptyList());
18  
19    public HandlingHistory(Collection<HandlingEvent> handlingEvents) {
20      Validate.notNull(handlingEvents, "Handling events are required");
21  
22      this.handlingEvents = new ArrayList<HandlingEvent>(handlingEvents);
23    }
24  
25    /**
26     * @return A distinct list (no duplicate registrations) of handling events, ordered by completion time.
27     */
28    public List<HandlingEvent> distinctEventsByCompletionTime() {
29      final List<HandlingEvent> ordered = new ArrayList<HandlingEvent>(
30        new HashSet<HandlingEvent>(handlingEvents)
31      );
32      sort(ordered, BY_COMPLETION_TIME_COMPARATOR);
33      return Collections.unmodifiableList(ordered);
34    }
35  
36    /**
37     * @return Most recently completed event, or null if the delivery history is empty.
38     */
39    public HandlingEvent mostRecentlyCompletedEvent() {
40      final List<HandlingEvent> distinctEvents = distinctEventsByCompletionTime();
41      if (distinctEvents.isEmpty()) {
42        return null;
43      } else {
44        return distinctEvents.get(distinctEvents.size() - 1);
45      }
46    }
47  
48    @Override
49    public boolean sameValueAs(HandlingHistory other) {
50      return other != null && this.handlingEvents.equals(other.handlingEvents);
51    }
52  
53    @Override
54    public boolean equals(Object o) {
55      if (this == o) return true;
56      if (o == null || getClass() != o.getClass()) return false;
57  
58      final HandlingHistory other = (HandlingHistory) o;
59      return sameValueAs(other);
60    }
61  
62    @Override
63    public int hashCode() {
64      return handlingEvents.hashCode();
65    }
66  
67    private static final Comparator<HandlingEvent> BY_COMPLETION_TIME_COMPARATOR =
68      new Comparator<HandlingEvent>() {
69        public int compare(final HandlingEvent he1, final HandlingEvent he2) {
70          return he1.completionTime().compareTo(he2.completionTime());
71        }
72      };
73  
74  }