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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  199.     }

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

  209. }