ImmutableTimeStampedCache.java

  1. /* Contributed in the public domain.
  2.  * Licensed to CS GROUP (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 java.util.stream.Stream;

  23. import org.hipparchus.exception.LocalizedCoreFormats;
  24. import org.hipparchus.util.FastMath;
  25. import org.orekit.errors.OrekitIllegalArgumentException;
  26. import org.orekit.errors.OrekitIllegalStateException;
  27. import org.orekit.errors.OrekitMessages;
  28. import org.orekit.errors.TimeStampedCacheException;
  29. import org.orekit.time.AbsoluteDate;
  30. import org.orekit.time.ChronologicalComparator;
  31. import org.orekit.time.TimeStamped;

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

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

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

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

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

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

  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.             final AbsoluteDate earliest = this.getEarliest().getDate();
  107.             throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_BEFORE,
  108.                     earliest, central, earliest.durationFrom(central));
  109.         } else if (i >= this.data.size()) {
  110.             final AbsoluteDate latest = this.getLatest().getDate();
  111.             throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_AFTER,
  112.                     latest, central, central.durationFrom(latest));
  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 this.data.subList(start, end).stream();
  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.     /** {@inheritDoc} */
  144.     public int getNeighborsSize() {
  145.         return this.neighborsSize;
  146.     }

  147.     /** {@inheritDoc} */
  148.     public T getEarliest() {
  149.         return this.data.get(0);
  150.     }

  151.     /** {@inheritDoc} */
  152.     public T getLatest() {
  153.         return this.data.get(this.data.size() - 1);
  154.     }

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

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

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

  174.         /** {@inheritDoc} */
  175.         @Override
  176.         public Stream<T> getNeighbors(final AbsoluteDate central) {
  177.             throw new TimeStampedCacheException(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 new OrekitIllegalStateException(OrekitMessages.NO_CACHED_ENTRIES);
  188.         }

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

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

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

  204.     }

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

  214. }