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 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.         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(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_BEFORE,
  108.                                                 this.getEarliest().getDate());
  109.         } else if (i >= this.data.size()) {
  110.             throw new TimeStampedCacheException(OrekitMessages.UNABLE_TO_GENERATE_NEW_DATA_AFTER,
  111.                                                 this.getLatest().getDate());
  112.         }

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

  118.         // return list without copying
  119.         return this.data.subList(start, end).stream();
  120.     }

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

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

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

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

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

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

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

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

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

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

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

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

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

  201.     }

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

  211. }