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.OrekitIllegalArgumentException;
  25. import org.orekit.errors.OrekitIllegalStateException;
  26. import org.orekit.errors.OrekitMessages;
  27. import org.orekit.errors.TimeStampedCacheException;
  28. import org.orekit.time.AbsoluteDate;
  29. import org.orekit.time.ChronologicalComparator;
  30. import org.orekit.time.TimeStamped;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  183.         /** {@inheritDoc} */
  184.         @Override
  185.         public T getEarliest() {
  186.             throw new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  187.         };

  188.         /** {@inheritDoc} */
  189.         @Override
  190.         public T getLatest() {
  191.             throw new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  192.         }

  193.         /** {@inheritDoc} */
  194.         @Override
  195.         public List<T> getAll() {
  196.             return Collections.emptyList();
  197.         }

  198.         /** {@inheritDoc} */
  199.         @Override
  200.         public String toString() {
  201.             return "Empty immutable cache";
  202.         }

  203.     };

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

  213. }