View Javadoc

1   package com.atlassian.johnson;
2   
3   import com.atlassian.johnson.event.Event;
4   
5   import javax.annotation.Nonnull;
6   import javax.annotation.ParametersAreNonnullByDefault;
7   import java.util.Collection;
8   import java.util.Collections;
9   import java.util.List;
10  import java.util.Optional;
11  import java.util.concurrent.CopyOnWriteArrayList;
12  import java.util.function.Predicate;
13  
14  import static com.google.common.base.Preconditions.checkNotNull;
15  import static java.util.stream.Collectors.toList;
16  
17  /**
18   * A default implementation of {@link JohnsonEventContainer} which stores events in a list.
19   * <p>
20   * Note: This implementation is thread-safe.
21   *
22   * @since 2.0
23   */
24  @ParametersAreNonnullByDefault
25  public class DefaultJohnsonEventContainer implements JohnsonEventContainer {
26  
27      private final List<Event> events = new CopyOnWriteArrayList<>();
28  
29      /**
30       * Adds the provided {@link Event} to the list.
31       *
32       * @param event the event to add
33       */
34      @Override
35      public void addEvent(final Event event) {
36          events.add(checkNotNull(event, "event"));
37      }
38  
39      /**
40       * Retrieves an <i>unmodifiable</i> view of the current {@link Event} list.
41       *
42       * @return an unmodifiable collection of zero or more events
43       */
44      @Nonnull
45      @Override
46      public List<Event> getEvents() {
47          return Collections.unmodifiableList(events);
48      }
49  
50      /**
51       * Retrieves a flag indicating whether there are any {@link Event}s in the list.
52       *
53       * @return {@code true} if the event list is not empty; otherwise, {@code false}
54       */
55      @Override
56      public boolean hasEvents() {
57          return !events.isEmpty();
58      }
59  
60      /**
61       * Removes the provided {@link Event} from the list, if it can be found.
62       *
63       * @param event the event to remove
64       */
65      @Override
66      public void removeEvent(final Event event) {
67          events.remove(checkNotNull(event, "event"));
68      }
69  
70      @Override
71      public Collection<Event> getEvents(final Predicate<? super Event> predicate) {
72          return events.stream().filter(predicate).collect(toList());
73      }
74  
75      @Override
76      public boolean hasEvent(final Predicate<? super Event> predicate) {
77          return !getEvents(predicate).isEmpty();
78      }
79  
80      @Override
81      public Optional<Event> firstEvent(final Predicate<? super Event> predicate) {
82          return getEvents(predicate).stream().findFirst();
83      }
84  }