1   package com.atlassian.pageobjects.elements.timeout;
2   
3   import java.util.Map;
4   
5   import com.google.common.collect.ImmutableMap;
6   
7   import static com.google.common.base.Preconditions.checkArgument;
8   import static com.google.common.base.Preconditions.checkNotNull;
9   
10  /**
11   * <p>
12   * {@link Timeouts} implementation based on simple mappings between timeout types and values.
13   *
14   * <p>
15   * At the very least, the provided map is supposed to contain timeout value for the {@link TimeoutType#DEFAULT}
16   * key. If it is not present, an exception will be raised from the constructor. This value will be used in place of
17   * whatever other timeout type that does have corresponding value within the properties.
18   *
19   */
20  public class MapBasedTimeouts implements Timeouts
21  {
22      private final Map<TimeoutType,Long> timeouts;
23      private final long defaultValue;
24  
25      public MapBasedTimeouts(final Map<TimeoutType, Long> timeouts)
26      {
27          this.timeouts = ImmutableMap.copyOf(checkNotNull(timeouts));
28          defaultValue = validateAndGetDefault();
29      }
30  
31      private long validateAndGetDefault()
32      {
33          checkArgument(timeouts.containsKey(TimeoutType.DEFAULT), "Must contain default timeout value");
34          checkArgument(timeouts.get(TimeoutType.DEFAULT) != null, "Must contain non-null default timeout value");
35          return timeouts.get(TimeoutType.DEFAULT);
36      }
37  
38      public long timeoutFor(final TimeoutType timeoutType)
39      {
40          Long timeout = timeouts.get(timeoutType);
41          if (timeout != null)
42          {
43              return timeout;
44          }
45          else if (TimeoutType.EVALUATION_INTERVAL == timeoutType)
46          {
47              return Timeouts.DEFAULT_INTERVAL;
48          }
49          else
50          {
51              return defaultValue;
52          }
53      }
54  }