ImmutableTimeStampedCache.java

  1. /* Contributed in the public domain.
  2.  * Licensed to CS Systèmes d'Information (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.utils;

  18. import java.util.ArrayList;
  19. import java.util.Collection;
  20. import java.util.Collections;
  21. import java.util.List;

  22. import org.apache.commons.math3.exception.util.LocalizedFormats;
  23. import org.apache.commons.math3.util.FastMath;
  24. import org.orekit.errors.OrekitException;
  25. import org.orekit.errors.OrekitMessages;
  26. import org.orekit.errors.TimeStampedCacheException;
  27. import org.orekit.time.AbsoluteDate;
  28. import org.orekit.time.ChronologicalComparator;
  29. import org.orekit.time.TimeStamped;

  30. /**
  31.  * A cache of {@link TimeStamped} data that provides concurrency through
  32.  * immutability. This strategy is suitable when all of the cached data is stored
  33.  * in memory. (For example, {@link org.orekit.time.UTCScale UTCScale}) This
  34.  * class then provides convenient methods for accessing the data.
  35.  *
  36.  * @author Evan Ward
  37.  * @param <T>  the type of data
  38.  */
  39. public class ImmutableTimeStampedCache<T extends TimeStamped>
  40.     implements TimeStampedCache<T> {

  41.     /**
  42.      * A single chronological comparator since instances are thread safe.
  43.      */
  44.     private static final ChronologicalComparator CMP = new ChronologicalComparator();

  45.     /**
  46.      * An empty immutable cache that always throws an exception on attempted
  47.      * access.
  48.      */
  49.     @SuppressWarnings("rawtypes")
  50.     private static final ImmutableTimeStampedCache EMPTY_CACHE =
  51.         new EmptyTimeStampedCache<TimeStamped>();

  52.     /**
  53.      * the cached data. Be careful not to modify it after the constructor, or
  54.      * return a reference that allows mutating this list.
  55.      */
  56.     private final List<T> data;

  57.     /**
  58.      * the size list to return from {@link #getNeighbors(AbsoluteDate)}.
  59.      */
  60.     private final int neighborsSize;

  61.     /**
  62.      * Create a new cache with the given neighbors size and data.
  63.      *
  64.      * @param neighborsSize the size of the list returned from
  65.      *        {@link #getNeighbors(AbsoluteDate)}. Must be less than or equal to
  66.      *        {@code data.size()}.
  67.      * @param data the backing data for this cache. The list will be copied to
  68.      *        ensure immutability. To guarantee immutability the entries in
  69.      *        {@code data} must be immutable themselves. There must be more data
  70.      *        than {@code neighborsSize}.
  71.      * @throws IllegalArgumentException if {@code neightborsSize > data.size()}
  72.      *         or if {@code neighborsSize} is negative
  73.      */
  74.     public ImmutableTimeStampedCache(final int neighborsSize,
  75.                                      final Collection<? extends T> data) {
  76.         // parameter check
  77.         if (neighborsSize > data.size()) {
  78.             throw OrekitException
  79.                 .createIllegalArgumentException(OrekitMessages.NOT_ENOUGH_CACHED_NEIGHBORS,
  80.                                                 data.size(), neighborsSize);
  81.         }
  82.         if (neighborsSize < 1) {
  83.             throw OrekitException
  84.                 .createIllegalArgumentException(LocalizedFormats.NUMBER_TOO_SMALL,
  85.                                                 neighborsSize, 0);
  86.         }

  87.         // assign instance variables
  88.         this.neighborsSize = neighborsSize;
  89.         // sort and copy data first
  90.         this.data = new ArrayList<T>(data);
  91.         Collections.sort(this.data, CMP);
  92.     }

  93.     /**
  94.      * private constructor for {@link #EMPTY_CACHE}.
  95.      */
  96.     private ImmutableTimeStampedCache() {
  97.         this.data = null;
  98.         this.neighborsSize = 0;
  99.     }

  100.     /** {@inheritDoc} */
  101.     public List<T> getNeighbors(final AbsoluteDate central)
  102.         throws TimeStampedCacheException {

  103.         // find central index
  104.         final int i = findIndex(central);

  105.         // check index in in the range of the data
  106.         if (i < 0) {
  107.             throw new TimeStampedCacheException(
  108.                                                 OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_BEFORE,
  109.                                                 this.getEarliest().getDate());
  110.         } else if (i >= this.data.size()) {
  111.             throw new TimeStampedCacheException(
  112.                                                 OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_AFTER,
  113.                                                 this.getLatest().getDate());
  114.         }

  115.         // force unbalanced range if necessary
  116.         int start = FastMath.max(0, i - (this.neighborsSize - 1) / 2);
  117.         final int end = FastMath.min(this.data.size(), start +
  118.                                                        this.neighborsSize);
  119.         start = end - this.neighborsSize;

  120.         // return list without copying
  121.         return Collections.unmodifiableList(this.data.subList(start, end));
  122.     }

  123.     /**
  124.      * Find the index, i, to {@link #data} such that {@code data[i] <= t} and
  125.      * {@code data[i+1] > t} if {@code data[i+1]} exists.
  126.      *
  127.      * @param t the time
  128.      * @return the index of the data at or just before {@code t}, {@code -1} if
  129.      *         {@code t} is before the first entry, or {@code data.size()} if
  130.      *         {@code t} is after the last entry.
  131.      */
  132.     private int findIndex(final AbsoluteDate t) {
  133.         // Guaranteed log(n) time
  134.         int i = Collections.binarySearch(this.data, t, CMP);
  135.         if (i == -this.data.size() - 1) {
  136.             // beyond last entry
  137.             i = this.data.size();
  138.         } else if (i < 0) {
  139.             // did not find exact match, but contained in data interval
  140.             i = -i - 2;
  141.         }
  142.         return i;
  143.     }

  144.     public int getNeighborsSize() {
  145.         return this.neighborsSize;
  146.     }

  147.     public T getEarliest() {
  148.         return this.data.get(0);
  149.     }

  150.     public T getLatest() {
  151.         return this.data.get(this.data.size() - 1);
  152.     }

  153.     /**
  154.      * Get all of the data in this cache.
  155.      *
  156.      * @return a sorted collection of all data passed in the
  157.      *         {@link #ImmutableTimeStampedCache(int, Collection) constructor}.
  158.      */
  159.     public List<T> getAll() {
  160.         return Collections.unmodifiableList(this.data);
  161.     }

  162.     /** {@inheritDoc} */
  163.     @Override
  164.     public String toString() {
  165.         return "Immutable cache with " + this.data.size() + " entries";
  166.     }

  167.     /**
  168.      * An empty immutable cache that always throws an exception on attempted
  169.      * access.
  170.      */
  171.     private static class EmptyTimeStampedCache<T extends TimeStamped> extends ImmutableTimeStampedCache<T> {

  172.         /** {@inheritDoc} */
  173.         @Override
  174.         public List<T> getNeighbors(final AbsoluteDate central)
  175.             throws TimeStampedCacheException {
  176.             throw new TimeStampedCacheException(
  177.                                                 OrekitMessages.NO_CACHED_ENTRIES);
  178.         };

  179.         /** {@inheritDoc} */
  180.         @Override
  181.         public int getNeighborsSize() {
  182.             return 0;
  183.         }

  184.         /** {@inheritDoc} */
  185.         @Override
  186.         public T getEarliest() {
  187.             throw OrekitException
  188.                 .createIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  189.         };

  190.         /** {@inheritDoc} */
  191.         @Override
  192.         public T getLatest() {
  193.             throw OrekitException
  194.                 .createIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  195.         }

  196.         /** {@inheritDoc} */
  197.         @Override
  198.         public List<T> getAll() {
  199.             return Collections.emptyList();
  200.         }

  201.         /** {@inheritDoc} */
  202.         @Override
  203.         public String toString() {
  204.             return "Empty immutable cache";
  205.         }

  206.     };

  207.     /**
  208.      * Get an empty immutable cache, cast to the correct type.
  209.      * @param <TS>  the type of data
  210.      * @return an empty {@link ImmutableTimeStampedCache}.
  211.      */
  212.     @SuppressWarnings("unchecked")
  213.     public static final <TS extends TimeStamped> ImmutableTimeStampedCache<TS> emptyCache() {
  214.         return (ImmutableTimeStampedCache<TS>) EMPTY_CACHE;
  215.     }

  216. }