DataProvidersManager.java

  1. /* Copyright 2002-2018 CS Systèmes d'Information
  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.data;

  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.text.ParseException;
  22. import java.util.ArrayList;
  23. import java.util.Collections;
  24. import java.util.Iterator;
  25. import java.util.LinkedHashSet;
  26. import java.util.List;
  27. import java.util.Set;
  28. import java.util.regex.Pattern;

  29. import org.orekit.errors.OrekitException;
  30. import org.orekit.errors.OrekitMessages;

  31. /** Singleton class managing all supported {@link DataProvider data providers}.

  32.  * <p>
  33.  * This class is the single point of access for all data loading features. It
  34.  * is used for example to load Earth Orientation Parameters used by IERS frames,
  35.  * to load UTC leap seconds used by time scales, to load planetary ephemerides ...
  36.  *
  37.  * <p>
  38.  * It is user-customizable: users can add their own data providers at will. This
  39.  * allows them for example to use a database or an existing data loading library
  40.  * in order to embed an Orekit enabled application in a global system with its
  41.  * own data handling mechanisms. There is no upper limitation on the number of
  42.  * providers, but often each application will use only a few.
  43.  * </p>
  44.  *
  45.  * <p>
  46.  * If the list of providers is empty when attempting to {@link #feed(String, DataLoader)
  47.  * feed} a file loader, the {@link #addDefaultProviders()} method is called
  48.  * automatically to set up a default configuration. This default configuration
  49.  * contains one {@link DataProvider data provider} for each component of the
  50.  * path-like list specified by the java property <code>orekit.data.path</code>.
  51.  * See the {@link #feed(String, DataLoader) feed} method documentation for further
  52.  * details. The default providers configuration is <em>not</em> set up if the list
  53.  * is not empty. If users want to have both the default providers and additional
  54.  * providers, they must call explicitly the {@link #addDefaultProviders()} method.
  55.  * </p>
  56.  *
  57.  * <p>
  58.  * The default configuration uses a predefined set of {@link DataFilter data filters}
  59.  * that already handled gzip-compressed files (recognized by the {@code .gz} suffix)
  60.  * and Unix-compressed files (recognized by the {@code .Z} suffix).
  61.  * Users can {@link #addFilter(DataFilter) add} custom filters for handling specific
  62.  * types of filters (decompression, deciphering...).
  63.  * </p>
  64.  *
  65.  * @author Luc Maisonobe
  66.  * @see DirectoryCrawler
  67.  * @see ClasspathCrawler
  68.  */
  69. public class DataProvidersManager {

  70.     /** Name of the property defining the root directories or zip/jar files path for default configuration. */
  71.     public static final String OREKIT_DATA_PATH = "orekit.data.path";

  72.     /** Supported data providers. */
  73.     private final List<DataProvider> providers;

  74.     /** Supported filters.
  75.      * @since 9.2
  76.      */
  77.     private final List<DataFilter> filters;

  78.     /** Number of predefined filters. */
  79.     private final int predefinedFilters;

  80.     /** Loaded data. */
  81.     private final Set<String> loaded;

  82.     /** Build an instance with default configuration.
  83.      * <p>
  84.      * This is a singleton, so the constructor is private.
  85.      * </p>
  86.      */
  87.     private DataProvidersManager() {
  88.         providers = new ArrayList<DataProvider>();
  89.         filters   = new ArrayList<>();
  90.         loaded    = new LinkedHashSet<String>();

  91.         // set up predefined filters
  92.         addFilter(new GzipFilter());
  93.         addFilter(new UnixCompressFilter());

  94.         predefinedFilters = filters.size();

  95.     }

  96.     /** Get the unique instance.
  97.      * @return unique instance of the manager.
  98.      */
  99.     public static DataProvidersManager getInstance() {
  100.         return LazyHolder.INSTANCE;
  101.     }

  102.     /** Add the default providers configuration.
  103.      * <p>
  104.      * The default configuration contains one {@link DataProvider data provider}
  105.      * for each component of the path-like list specified by the java property
  106.      * <code>orekit.data.path</code>.
  107.      * </p>
  108.      * <p>
  109.      * If the property is not set or is null, no data will be available to the library
  110.      * (for example no pole corrections will be applied and only predefined UTC steps
  111.      * will be taken into account). No errors will be triggered in this case.
  112.      * </p>
  113.      * <p>
  114.      * If the property is set, it must contains a list of existing directories or zip/jar
  115.      * archives. One {@link DirectoryCrawler} instance will be set up for each
  116.      * directory and one {@link ZipJarCrawler} instance (configured to look for the
  117.      * archive in the filesystem) will be set up for each zip/jar archive. The list
  118.      * elements in the java property are separated using the standard path separator for
  119.      * the operating system as returned by {@link System#getProperty(String)
  120.      * System.getProperty("path.separator")}. This standard path separator is ":" on
  121.      * Linux and Unix type systems and ";" on Windows types systems.
  122.      * </p>
  123.      * @exception OrekitException if an element of the list does not exist or exists but
  124.      * is neither a directory nor a zip/jar archive
  125.      */
  126.     public void addDefaultProviders() throws OrekitException {

  127.         // get the path containing all components
  128.         final String path = System.getProperty(OREKIT_DATA_PATH);
  129.         if ((path != null) && !"".equals(path)) {

  130.             // extract the various components
  131.             for (final String name : path.split(System.getProperty("path.separator"))) {
  132.                 if (!"".equals(name)) {

  133.                     final File file = new File(name);

  134.                     // check component
  135.                     if (!file.exists()) {
  136.                         if (DataProvider.ZIP_ARCHIVE_PATTERN.matcher(name).matches()) {
  137.                             throw new OrekitException(OrekitMessages.UNABLE_TO_FIND_FILE, name);
  138.                         } else {
  139.                             throw new OrekitException(OrekitMessages.DATA_ROOT_DIRECTORY_DOES_NOT_EXIST, name);
  140.                         }
  141.                     }

  142.                     if (file.isDirectory()) {
  143.                         addProvider(new DirectoryCrawler(file));
  144.                     } else if (DataProvider.ZIP_ARCHIVE_PATTERN.matcher(name).matches()) {
  145.                         addProvider(new ZipJarCrawler(file));
  146.                     } else {
  147.                         throw new OrekitException(OrekitMessages.NEITHER_DIRECTORY_NOR_ZIP_OR_JAR, name);
  148.                     }

  149.                 }
  150.             }
  151.         }

  152.     }

  153.     /** Add a data provider to the supported list.
  154.      * @param provider data provider to add
  155.      * @see #removeProvider(DataProvider)
  156.      * @see #clearProviders()
  157.      * @see #isSupported(DataProvider)
  158.      * @see #getProviders()
  159.      */
  160.     public void addProvider(final DataProvider provider) {
  161.         providers.add(provider);
  162.     }

  163.     /** Remove one provider.
  164.      * @param provider provider instance to remove
  165.      * @return instance removed (null if the provider was not already present)
  166.      * @see #addProvider(DataProvider)
  167.      * @see #clearProviders()
  168.      * @see #isSupported(DataProvider)
  169.      * @see #getProviders()
  170.      * @since 5.1
  171.      */
  172.     public DataProvider removeProvider(final DataProvider provider) {
  173.         for (final Iterator<DataProvider> iterator = providers.iterator(); iterator.hasNext();) {
  174.             final DataProvider current = iterator.next();
  175.             if (current == provider) {
  176.                 iterator.remove();
  177.                 return provider;
  178.             }
  179.         }
  180.         return null;
  181.     }

  182.     /** Remove all data providers.
  183.      * @see #addProvider(DataProvider)
  184.      * @see #removeProvider(DataProvider)
  185.      * @see #isSupported(DataProvider)
  186.      * @see #getProviders()
  187.      */
  188.     public void clearProviders() {
  189.         providers.clear();
  190.     }

  191.     /** Add a data filter.
  192.      * @param filter filter to add
  193.      * @see #applyAllFilters(NamedData)
  194.      * @see #clearFilters()
  195.      * @since 9.2
  196.      */
  197.     public void addFilter(final DataFilter filter) {
  198.         filters.add(filter);
  199.     }

  200.     /** Remove all data filters, except the predefined ones.
  201.      * @see #addFilter(DataFilter)
  202.      * @since 9.2
  203.      */
  204.     public void clearFilters() {
  205.         for (int i = filters.size() - 1; i >= predefinedFilters; --i) {
  206.             filters.remove(i);
  207.         }
  208.     }

  209.     /** Apply all the relevant data filters, taking care of layers.
  210.      * <p>
  211.      * If several filters can be applied, they will all be applied
  212.      * as a stack, even recursively if required. This means that if
  213.      * filter A applies to files with names of the form base.ext.a
  214.      * and filter B applies to files with names of the form base.ext.b,
  215.      * then providing base.ext.a.b.a will result in filter A being
  216.      * applied on top of filter B which itself is applied on top of
  217.      * another instance of filter A.
  218.      * </p>
  219.      * @param original original named data
  220.      * @return fully filtered named data
  221.      * @exception IOException if some data stream cannot be filtered
  222.      * @see #addFilter(DataFilter)
  223.      * @see #clearFilters()
  224.      * @since 9.2
  225.      */
  226.     public NamedData applyAllFilters(final NamedData original)
  227.         throws IOException {
  228.         NamedData top = original;
  229.         for (boolean filtering = true; filtering;) {
  230.             filtering = false;
  231.             for (final DataFilter filter : filters) {
  232.                 final NamedData filtered = filter.filter(top);
  233.                 if (filtered != top) {
  234.                     // the filter has been applied, we need to restart the loop
  235.                     top       = filtered;
  236.                     filtering = true;
  237.                     break;
  238.                 }
  239.             }
  240.         }
  241.         return top;
  242.     }

  243.     /** Check if some provider is supported.
  244.      * @param provider provider to check
  245.      * @return true if the specified provider instance is already in the supported list
  246.      * @see #addProvider(DataProvider)
  247.      * @see #removeProvider(DataProvider)
  248.      * @see #clearProviders()
  249.      * @see #getProviders()
  250.      * @since 5.1
  251.      */
  252.     public boolean isSupported(final DataProvider provider) {
  253.         for (final DataProvider current : providers) {
  254.             if (current == provider) {
  255.                 return true;
  256.             }
  257.         }
  258.         return false;
  259.     }

  260.     /** Get an unmodifiable view of the list of supported providers.
  261.      * @return unmodifiable view of the list of supported providers
  262.      * @see #addProvider(DataProvider)
  263.      * @see #removeProvider(DataProvider)
  264.      * @see #clearProviders()
  265.      * @see #isSupported(DataProvider)
  266.      */
  267.     public List<DataProvider> getProviders() {
  268.         return Collections.unmodifiableList(providers);
  269.     }

  270.     /** Get an unmodifiable view of the set of data file names that have been loaded.
  271.      * <p>
  272.      * The names returned are exactly the ones that were given to the {@link
  273.      * DataLoader#loadData(InputStream, String) DataLoader.loadData} method.
  274.      * </p>
  275.      * @return unmodifiable view of the set of data file names that have been loaded
  276.      * @see #feed(String, DataLoader)
  277.      * @see #clearLoadedDataNames()
  278.      */
  279.     public Set<String> getLoadedDataNames() {
  280.         return Collections.unmodifiableSet(loaded);
  281.     }

  282.     /** Clear the set of data file names that have been loaded.
  283.      * @see #getLoadedDataNames()
  284.      */
  285.     public void clearLoadedDataNames() {
  286.         loaded.clear();
  287.     }

  288.     /** Feed a data file loader by browsing all data providers.
  289.      * <p>
  290.      * If this method is called with an empty list of providers, a default
  291.      * providers configuration is set up. This default configuration contains
  292.      * only one {@link DataProvider data provider}: a {@link DirectoryCrawler}
  293.      * instance that loads data from files located somewhere in a directory hierarchy.
  294.      * This default provider is <em>not</em> added if the list is not empty. If users
  295.      * want to have both the default provider and other providers, they must add it
  296.      * explicitly.
  297.      * </p>
  298.      * <p>
  299.      * The providers are used in the order in which they were {@link #addProvider(DataProvider)
  300.      * added}. As soon as one provider is able to feed the data loader, the loop is
  301.      * stopped. If no provider is able to feed the data loader, then the last error
  302.      * triggered is thrown.
  303.      * </p>
  304.      * @param supportedNames regular expression for file names supported by the visitor
  305.      * @param loader data loader to use
  306.      * @return true if some data has been loaded
  307.      * @exception OrekitException if the data loader cannot be fed (read error ...)
  308.      * or if the default configuration cannot be set up
  309.      */
  310.     public boolean feed(final String supportedNames, final DataLoader loader)
  311.         throws OrekitException {

  312.         final Pattern supported = Pattern.compile(supportedNames);

  313.         // set up a default configuration if no providers have been set
  314.         if (providers.isEmpty()) {
  315.             addDefaultProviders();
  316.         }

  317.         // monitor the data that the loader will load
  318.         final DataLoader monitoredLoader = new MonitoringWrapper(loader);

  319.         // crawl the data collection
  320.         OrekitException delayedException = null;
  321.         for (final DataProvider provider : providers) {
  322.             try {

  323.                 // try to feed the visitor using the current provider
  324.                 if (provider.feed(supported, monitoredLoader)) {
  325.                     return true;
  326.                 }

  327.             } catch (OrekitException oe) {
  328.                 // remember the last error encountered
  329.                 delayedException = oe;
  330.             }
  331.         }

  332.         if (delayedException != null) {
  333.             throw delayedException;
  334.         }

  335.         return false;

  336.     }

  337.     /** Data loading monitoring wrapper class. */
  338.     private class MonitoringWrapper implements DataLoader {

  339.         /** Wrapped loader. */
  340.         private final DataLoader loader;

  341.         /** Simple constructor.
  342.          * @param loader loader to monitor
  343.          */
  344.         MonitoringWrapper(final DataLoader loader) {
  345.             this.loader = loader;
  346.         }

  347.         /** {@inheritDoc} */
  348.         public boolean stillAcceptsData() {
  349.             // delegate to monitored loader
  350.             return loader.stillAcceptsData();
  351.         }

  352.         /** {@inheritDoc} */
  353.         public void loadData(final InputStream input, final String name)
  354.             throws IOException, ParseException, OrekitException {

  355.             // delegate to monitored loader
  356.             loader.loadData(input, name);

  357.             // monitor the fact new data has been loaded
  358.             loaded.add(name);

  359.         }

  360.     }

  361.     /** Holder for the manager singleton.
  362.      * <p>
  363.      * We use the Initialization on demand holder idiom to store
  364.      * the singletons, as it is both thread-safe, efficient (no
  365.      * synchronization) and works with all versions of java.
  366.      * </p>
  367.      */
  368.     private static class LazyHolder {

  369.         /** Unique instance. */
  370.         private static final DataProvidersManager INSTANCE = new DataProvidersManager();

  371.         /** Private constructor.
  372.          * <p>This class is a utility class, it should neither have a public
  373.          * nor a default constructor. This private constructor prevents
  374.          * the compiler from generating one automatically.</p>
  375.          */
  376.         private LazyHolder() {
  377.         }

  378.     }

  379. }