DataProvidersManager.java

  1. /* Copyright 2002-2020 CS GROUP
  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.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.annotation.DefaultDataContext;
  30. import org.orekit.errors.OrekitException;
  31. import org.orekit.errors.OrekitMessages;
  32. import org.orekit.gnss.HatanakaCompressFilter;

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

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

  74.     /** Supported data providers. */
  75.     private final List<DataProvider> providers;

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

  80.     /** Number of predefined filters. */
  81.     private final int predefinedFilters;

  82.     /** Loaded data. */
  83.     private final Set<String> loaded;

  84.     /** Build an instance with default configuration. */
  85.     public DataProvidersManager() {
  86.         providers = new ArrayList<>();
  87.         filters   = new ArrayList<>();
  88.         loaded    = new LinkedHashSet<>();

  89.         // set up predefined filters
  90.         addFilter(new GzipFilter());
  91.         addFilter(new UnixCompressFilter());
  92.         addFilter(new HatanakaCompressFilter());

  93.         predefinedFilters = filters.size();

  94.     }

  95.     /**
  96.      * Get the default instance.
  97.      *
  98.      * @return default instance of the manager.
  99.      * @see DataContext
  100.      * @deprecated This class is no longer a singleton. In order to support loading
  101.      * multiple data sets code should be updated to accept an instance of this class. If
  102.      * you need to maintain compatibility with Orekit 10.0's behavior use the default data
  103.      * context: {@code DataContext.getDefault().getDataProvidersManager()}.
  104.      */
  105.     @Deprecated
  106.     @DefaultDataContext
  107.     public static DataProvidersManager getInstance() {
  108.         return DataContext.getDefault().getDataProvidersManager();
  109.     }

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

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

  136.             // extract the various components
  137.             for (final String name : path.split(System.getProperty("path.separator"))) {
  138.                 if (!"".equals(name)) {

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

  140.                     // check component
  141.                     if (!file.exists()) {
  142.                         if (DataProvider.ZIP_ARCHIVE_PATTERN.matcher(name).matches()) {
  143.                             throw new OrekitException(OrekitMessages.UNABLE_TO_FIND_FILE, name);
  144.                         } else {
  145.                             throw new OrekitException(OrekitMessages.DATA_ROOT_DIRECTORY_DOES_NOT_EXIST, name);
  146.                         }
  147.                     }

  148.                     if (file.isDirectory()) {
  149.                         addProvider(new DirectoryCrawler(file));
  150.                     } else if (DataProvider.ZIP_ARCHIVE_PATTERN.matcher(name).matches()) {
  151.                         addProvider(new ZipJarCrawler(file));
  152.                     } else {
  153.                         throw new OrekitException(OrekitMessages.NEITHER_DIRECTORY_NOR_ZIP_OR_JAR, name);
  154.                     }

  155.                 }
  156.             }
  157.         }

  158.     }

  159.     /** Add a data provider to the supported list.
  160.      * @param provider data provider to add
  161.      * @see #removeProvider(DataProvider)
  162.      * @see #clearProviders()
  163.      * @see #isSupported(DataProvider)
  164.      * @see #getProviders()
  165.      */
  166.     public void addProvider(final DataProvider provider) {
  167.         providers.add(provider);
  168.     }

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

  188.     /** Remove all data providers.
  189.      * @see #addProvider(DataProvider)
  190.      * @see #removeProvider(DataProvider)
  191.      * @see #isSupported(DataProvider)
  192.      * @see #getProviders()
  193.      */
  194.     public void clearProviders() {
  195.         providers.clear();
  196.     }

  197.     /** Add a data filter.
  198.      * @param filter filter to add
  199.      * @see #applyAllFilters(NamedData)
  200.      * @see #clearFilters()
  201.      * @since 9.2
  202.      */
  203.     public void addFilter(final DataFilter filter) {
  204.         filters.add(filter);
  205.     }

  206.     /** Remove all data filters, except the predefined ones.
  207.      * @see #addFilter(DataFilter)
  208.      * @since 9.2
  209.      */
  210.     public void clearFilters() {
  211.         filters.subList(predefinedFilters, filters.size()).clear();
  212.     }

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

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

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

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

  286.     /** Clear the set of data file names that have been loaded.
  287.      * @see #getLoadedDataNames()
  288.      */
  289.     public void clearLoadedDataNames() {
  290.         loaded.clear();
  291.     }

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

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

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

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

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

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

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

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

  336.         return false;

  337.     }

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

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

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

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

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

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

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

  360.         }

  361.     }

  362. }