RapidDataAndPredictionXMLLoader.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.frames;

  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.InputStreamReader;
  21. import java.nio.charset.StandardCharsets;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.List;
  25. import java.util.SortedSet;
  26. import java.util.function.Supplier;

  27. import javax.xml.parsers.ParserConfigurationException;
  28. import javax.xml.parsers.SAXParserFactory;

  29. import org.hipparchus.exception.LocalizedCoreFormats;
  30. import org.orekit.data.DataProvidersManager;
  31. import org.orekit.errors.OrekitException;
  32. import org.orekit.errors.OrekitMessages;
  33. import org.orekit.time.AbsoluteDate;
  34. import org.orekit.time.DateComponents;
  35. import org.orekit.time.TimeScale;
  36. import org.orekit.utils.Constants;
  37. import org.orekit.utils.IERSConventions;
  38. import org.xml.sax.Attributes;
  39. import org.xml.sax.InputSource;
  40. import org.xml.sax.SAXException;
  41. import org.xml.sax.XMLReader;
  42. import org.xml.sax.helpers.DefaultHandler;

  43. /** Loader for IERS rapid data and prediction file in XML format (finals file).
  44.  * <p>Rapid data and prediction file contain {@link EOPEntry
  45.  * Earth Orientation Parameters} for several years periods, in one file
  46.  * only that is updated regularly.</p>
  47.  * <p>The XML EOP files are recognized thanks to their base names, which
  48.  * must match one of the the patterns <code>finals.2000A.*.xml</code> or
  49.  * <code>finals.*.xml</code> (or the same ending with <code>.gz</code> for
  50.  * gzip-compressed files) where * stands for a word like "all", "daily",
  51.  * or "data".</p>
  52.  * <p>Files containing data (back to 1973) are available at IERS web site: <a
  53.  * href="http://www.iers.org/IERS/EN/DataProducts/EarthOrientationData/eop.html">Earth orientation data</a>.</p>
  54.  * <p>
  55.  * This class is immutable and hence thread-safe
  56.  * </p>
  57.  * @author Luc Maisonobe
  58.  */
  59. class RapidDataAndPredictionXMLLoader extends AbstractEopLoader
  60.         implements EOPHistoryLoader {

  61.     /** Conversion factor for milli-arc seconds entries. */
  62.     private static final double MILLI_ARC_SECONDS_TO_RADIANS = Constants.ARC_SECONDS_TO_RADIANS / 1000.0;

  63.     /** Conversion factor for milli seconds entries. */
  64.     private static final double MILLI_SECONDS_TO_SECONDS = 1.0 / 1000.0;

  65.     /**
  66.      * Build a loader for IERS XML EOP files.
  67.      *
  68.      * @param supportedNames regular expression for supported files names
  69.      * @param manager        provides access to the XML EOP files.
  70.      * @param utcSupplier    UTC time scale.
  71.      */
  72.     RapidDataAndPredictionXMLLoader(final String supportedNames,
  73.                                     final DataProvidersManager manager,
  74.                                     final Supplier<TimeScale> utcSupplier) {
  75.         super(supportedNames, manager, utcSupplier);
  76.     }

  77.     /** {@inheritDoc} */
  78.     public void fillHistory(final IERSConventions.NutationCorrectionConverter converter,
  79.                             final SortedSet<EOPEntry> history) {
  80.         final ItrfVersionProvider itrfVersionProvider = new ITRFVersionLoader(
  81.                 ITRFVersionLoader.SUPPORTED_NAMES,
  82.                 getDataProvidersManager());
  83.         final Parser parser = new Parser(converter, itrfVersionProvider, getUtc());
  84.         final EopParserLoader loader = new EopParserLoader(parser);
  85.         this.feed(loader);
  86.         history.addAll(loader.getEop());
  87.     }

  88.     /** Internal class performing the parsing. */
  89.     static class Parser extends AbstractEopParser {

  90.         /** History entries. */
  91.         private List<EOPEntry> history;

  92.         /**
  93.          * Simple constructor.
  94.          *
  95.          * @param converter           converter to use
  96.          * @param itrfVersionProvider to use for determining the ITRF version of the EOP.
  97.          * @param utc                 time scale for parsing dates.
  98.          */
  99.         Parser(final IERSConventions.NutationCorrectionConverter converter,
  100.                final ItrfVersionProvider itrfVersionProvider,
  101.                final TimeScale utc) {
  102.             super(converter, itrfVersionProvider, utc);
  103.         }

  104.         /** {@inheritDoc} */
  105.         @Override
  106.         public Collection<EOPEntry> parse(final InputStream input, final String name)
  107.             throws IOException, OrekitException {
  108.             try {
  109.                 this.history = new ArrayList<>();
  110.                 // set up a reader for line-oriented bulletin B files
  111.                 final XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  112.                 reader.setContentHandler(new EOPContentHandler(name));
  113.                 // disable external entities
  114.                 reader.setEntityResolver((publicId, systemId) -> new InputSource());

  115.                 // read all file, ignoring header
  116.                 reader.parse(new InputSource(new InputStreamReader(input, StandardCharsets.UTF_8)));

  117.                 return history;

  118.             } catch (SAXException se) {
  119.                 if ((se.getCause() != null) && (se.getCause() instanceof OrekitException)) {
  120.                     throw (OrekitException) se.getCause();
  121.                 }
  122.                 throw new OrekitException(se, LocalizedCoreFormats.SIMPLE_MESSAGE, se.getMessage());
  123.             } catch (ParserConfigurationException pce) {
  124.                 throw new OrekitException(pce, LocalizedCoreFormats.SIMPLE_MESSAGE, pce.getMessage());
  125.             }
  126.         }

  127.         /** Local content handler for XML EOP files. */
  128.         private class EOPContentHandler extends DefaultHandler {

  129.             // CHECKSTYLE: stop JavadocVariable check

  130.             // elements and attributes used in both daily and finals data files
  131.             private static final String MJD_ELT           = "MJD";
  132.             private static final String LOD_ELT           = "LOD";
  133.             private static final String X_ELT             = "X";
  134.             private static final String Y_ELT             = "Y";
  135.             private static final String DPSI_ELT          = "dPsi";
  136.             private static final String DEPSILON_ELT      = "dEpsilon";
  137.             private static final String DX_ELT            = "dX";
  138.             private static final String DY_ELT            = "dY";

  139.             // elements and attributes specific to daily data files
  140.             private static final String DATA_EOP_ELT      = "dataEOP";
  141.             private static final String TIME_SERIES_ELT   = "timeSeries";
  142.             private static final String DATE_YEAR_ELT     = "dateYear";
  143.             private static final String DATE_MONTH_ELT    = "dateMonth";
  144.             private static final String DATE_DAY_ELT      = "dateDay";
  145.             private static final String POLE_ELT          = "pole";
  146.             private static final String UT_ELT            = "UT";
  147.             private static final String UT1_U_UTC_ELT     = "UT1_UTC";
  148.             private static final String NUTATION_ELT      = "nutation";
  149.             private static final String SOURCE_ATTR       = "source";
  150.             private static final String BULLETIN_A_SOURCE = "BulletinA";

  151.             // elements and attributes specific to finals data files
  152.             private static final String FINALS_ELT        = "Finals";
  153.             private static final String DATE_ELT          = "date";
  154.             private static final String EOP_SET_ELT       = "EOPSet";
  155.             private static final String BULLETIN_A_ELT    = "bulletinA";
  156.             private static final String UT1_M_UTC_ELT     = "UT1-UTC";

  157.             private boolean inBulletinA;
  158.             private int     year;
  159.             private int     month;
  160.             private int     day;
  161.             private int     mjd;
  162.             private AbsoluteDate mjdDate;
  163.             private double  dtu1;
  164.             private double  lod;
  165.             private double  x;
  166.             private double  y;
  167.             private double  dpsi;
  168.             private double  deps;
  169.             private double  dx;
  170.             private double  dy;

  171.             // CHECKSTYLE: resume JavadocVariable check

  172.             /** File name. */
  173.             private final String name;

  174.             /** Buffer for read characters. */
  175.             private final StringBuffer buffer;

  176.             /** Indicator for daily data XML format or final data XML format. */
  177.             private DataFileContent content;

  178.             /** ITRF version configuration. */
  179.             private ITRFVersionLoader.ITRFVersionConfiguration configuration;

  180.             /** Simple constructor.
  181.              * @param name file name
  182.              */
  183.             EOPContentHandler(final String name) {
  184.                 this.name   = name;
  185.                 this.buffer = new StringBuffer();
  186.             }

  187.             /** {@inheritDoc} */
  188.             @Override
  189.             public void startDocument() {
  190.                 content       = DataFileContent.UNKNOWN;
  191.                 configuration = null;
  192.             }

  193.             /** {@inheritDoc} */
  194.             @Override
  195.             public void characters(final char[] ch, final int start, final int length) {
  196.                 buffer.append(ch, start, length);
  197.             }

  198.             /** {@inheritDoc} */
  199.             @Override
  200.             public void startElement(final String uri, final String localName,
  201.                                      final String qName, final Attributes atts) {

  202.                 // reset the buffer to empty
  203.                 buffer.delete(0, buffer.length());

  204.                 if (content == DataFileContent.UNKNOWN) {
  205.                     // try to identify file content
  206.                     if (qName.equals(TIME_SERIES_ELT)) {
  207.                         // the file contains final data
  208.                         content = DataFileContent.DAILY;
  209.                     } else if (qName.equals(FINALS_ELT)) {
  210.                         // the file contains final data
  211.                         content = DataFileContent.FINAL;
  212.                     }
  213.                 }

  214.                 if (content == DataFileContent.DAILY) {
  215.                     startDailyElement(qName, atts);
  216.                 } else if (content == DataFileContent.FINAL) {
  217.                     startFinalElement(qName);
  218.                 }

  219.             }

  220.             /** Handle end of an element in a daily data file.
  221.              * @param qName name of the element
  222.              * @param atts element attributes
  223.              */
  224.             private void startDailyElement(final String qName, final Attributes atts) {
  225.                 if (qName.equals(TIME_SERIES_ELT)) {
  226.                     // reset EOP data
  227.                     resetEOPData();
  228.                 } else if (qName.equals(POLE_ELT) || qName.equals(UT_ELT) || qName.equals(NUTATION_ELT)) {
  229.                     final String source = atts.getValue(SOURCE_ATTR);
  230.                     if (source != null) {
  231.                         inBulletinA = source.equals(BULLETIN_A_SOURCE);
  232.                     }
  233.                 }
  234.             }

  235.             /** Handle end of an element in a final data file.
  236.              * @param qName name of the element
  237.              */
  238.             private void startFinalElement(final String qName) {
  239.                 if (qName.equals(EOP_SET_ELT)) {
  240.                     // reset EOP data
  241.                     resetEOPData();
  242.                 } else if (qName.equals(BULLETIN_A_ELT)) {
  243.                     inBulletinA = true;
  244.                 }
  245.             }

  246.             /** Reset EOP data.
  247.              */
  248.             private void resetEOPData() {
  249.                 inBulletinA = false;
  250.                 year        = -1;
  251.                 month       = -1;
  252.                 day         = -1;
  253.                 mjd         = -1;
  254.                 mjdDate     = null;
  255.                 dtu1        = Double.NaN;
  256.                 lod         = Double.NaN;
  257.                 x           = Double.NaN;
  258.                 y           = Double.NaN;
  259.                 dpsi        = Double.NaN;
  260.                 deps        = Double.NaN;
  261.                 dx          = Double.NaN;
  262.                 dy          = Double.NaN;
  263.             }

  264.             /** {@inheritDoc} */
  265.             @Override
  266.             public void endElement(final String uri, final String localName, final String qName)
  267.                 throws SAXException {
  268.                 try {
  269.                     if (content == DataFileContent.DAILY) {
  270.                         endDailyElement(qName);
  271.                     } else if (content == DataFileContent.FINAL) {
  272.                         endFinalElement(qName);
  273.                     }
  274.                 } catch (OrekitException oe) {
  275.                     throw new SAXException(oe);
  276.                 }
  277.             }

  278.             /** Handle end of an element in a daily data file.
  279.              * @param qName name of the element
  280.              */
  281.             private void endDailyElement(final String qName) {
  282.                 if (qName.equals(DATE_YEAR_ELT) && (buffer.length() > 0)) {
  283.                     year = Integer.parseInt(buffer.toString());
  284.                 } else if (qName.equals(DATE_MONTH_ELT) && (buffer.length() > 0)) {
  285.                     month = Integer.parseInt(buffer.toString());
  286.                 } else if (qName.equals(DATE_DAY_ELT) && (buffer.length() > 0)) {
  287.                     day = Integer.parseInt(buffer.toString());
  288.                 } else if (qName.equals(MJD_ELT) && (buffer.length() > 0)) {
  289.                     mjd     = Integer.parseInt(buffer.toString());
  290.                     mjdDate = new AbsoluteDate(new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  291.                                                getUtc());
  292.                 } else if (qName.equals(UT1_M_UTC_ELT)) {
  293.                     dtu1 = overwrite(dtu1, 1.0);
  294.                 } else if (qName.equals(LOD_ELT)) {
  295.                     lod = overwrite(lod, MILLI_SECONDS_TO_SECONDS);
  296.                 } else if (qName.equals(X_ELT)) {
  297.                     x = overwrite(x, Constants.ARC_SECONDS_TO_RADIANS);
  298.                 } else if (qName.equals(Y_ELT)) {
  299.                     y = overwrite(y, Constants.ARC_SECONDS_TO_RADIANS);
  300.                 } else if (qName.equals(DPSI_ELT)) {
  301.                     dpsi = overwrite(dpsi, MILLI_ARC_SECONDS_TO_RADIANS);
  302.                 } else if (qName.equals(DEPSILON_ELT)) {
  303.                     deps = overwrite(deps, MILLI_ARC_SECONDS_TO_RADIANS);
  304.                 } else if (qName.equals(DX_ELT)) {
  305.                     dx   = overwrite(dx, MILLI_ARC_SECONDS_TO_RADIANS);
  306.                 } else if (qName.equals(DY_ELT)) {
  307.                     dy   = overwrite(dy, MILLI_ARC_SECONDS_TO_RADIANS);
  308.                 } else if (qName.equals(POLE_ELT) || qName.equals(UT_ELT) || qName.equals(NUTATION_ELT)) {
  309.                     inBulletinA = false;
  310.                 } else if (qName.equals(DATA_EOP_ELT)) {
  311.                     checkDates();
  312.                     if ((!Double.isNaN(dtu1)) && (!Double.isNaN(lod)) && (!Double.isNaN(x)) && (!Double.isNaN(y))) {
  313.                         final double[] equinox;
  314.                         final double[] nro;
  315.                         if (Double.isNaN(dpsi)) {
  316.                             nro = new double[] {
  317.                                 dx, dy
  318.                             };
  319.                             equinox = getConverter().toEquinox(mjdDate, nro[0], nro[1]);
  320.                         } else {
  321.                             equinox = new double[] {
  322.                                 dpsi, deps
  323.                             };
  324.                             nro = getConverter().toNonRotating(mjdDate, equinox[0], equinox[1]);
  325.                         }
  326.                         if (configuration == null || !configuration.isValid(mjd)) {
  327.                             // get a configuration for current name and date range
  328.                             configuration = getItrfVersionProvider().getConfiguration(name, mjd);
  329.                         }
  330.                         history.add(new EOPEntry(mjd, dtu1, lod, x, y, equinox[0], equinox[1], nro[0], nro[1],
  331.                                                  configuration.getVersion(), mjdDate));
  332.                     }
  333.                 }
  334.             }

  335.             /** Handle end of an element in a final data file.
  336.              * @param qName name of the element
  337.              */
  338.             private void endFinalElement(final String qName) {
  339.                 if (qName.equals(DATE_ELT) && (buffer.length() > 0)) {
  340.                     final String[] fields = buffer.toString().split("-");
  341.                     if (fields.length == 3) {
  342.                         year  = Integer.parseInt(fields[0]);
  343.                         month = Integer.parseInt(fields[1]);
  344.                         day   = Integer.parseInt(fields[2]);
  345.                     }
  346.                 } else if (qName.equals(MJD_ELT) && (buffer.length() > 0)) {
  347.                     mjd     = Integer.parseInt(buffer.toString());
  348.                     mjdDate = new AbsoluteDate(new DateComponents(DateComponents.MODIFIED_JULIAN_EPOCH, mjd),
  349.                                                getUtc());
  350.                 } else if (qName.equals(UT1_U_UTC_ELT)) {
  351.                     dtu1 = overwrite(dtu1, 1.0);
  352.                 } else if (qName.equals(LOD_ELT)) {
  353.                     lod = overwrite(lod, MILLI_SECONDS_TO_SECONDS);
  354.                 } else if (qName.equals(X_ELT)) {
  355.                     x = overwrite(x, Constants.ARC_SECONDS_TO_RADIANS);
  356.                 } else if (qName.equals(Y_ELT)) {
  357.                     y = overwrite(y, Constants.ARC_SECONDS_TO_RADIANS);
  358.                 } else if (qName.equals(DPSI_ELT)) {
  359.                     dpsi = overwrite(dpsi, MILLI_ARC_SECONDS_TO_RADIANS);
  360.                 } else if (qName.equals(DEPSILON_ELT)) {
  361.                     deps = overwrite(deps, MILLI_ARC_SECONDS_TO_RADIANS);
  362.                 } else if (qName.equals(DX_ELT)) {
  363.                     dx   = overwrite(dx, MILLI_ARC_SECONDS_TO_RADIANS);
  364.                 } else if (qName.equals(DY_ELT)) {
  365.                     dy   = overwrite(dy, MILLI_ARC_SECONDS_TO_RADIANS);
  366.                 } else if (qName.equals(BULLETIN_A_ELT)) {
  367.                     inBulletinA = false;
  368.                 } else if (qName.equals(EOP_SET_ELT)) {
  369.                     checkDates();
  370.                     if ((!Double.isNaN(dtu1)) && (!Double.isNaN(lod)) && (!Double.isNaN(x)) && (!Double.isNaN(y))) {
  371.                         final double[] equinox;
  372.                         final double[] nro;
  373.                         if (Double.isNaN(dpsi)) {
  374.                             nro = new double[] {
  375.                                 dx, dy
  376.                             };
  377.                             equinox = getConverter().toEquinox(mjdDate, nro[0], nro[1]);
  378.                         } else {
  379.                             equinox = new double[] {
  380.                                 dpsi, deps
  381.                             };
  382.                             nro = getConverter().toNonRotating(mjdDate, equinox[0], equinox[1]);
  383.                         }
  384.                         if (configuration == null || !configuration.isValid(mjd)) {
  385.                             // get a configuration for current name and date range
  386.                             configuration = getItrfVersionProvider().getConfiguration(name, mjd);
  387.                         }
  388.                         history.add(new EOPEntry(mjd, dtu1, lod, x, y, equinox[0], equinox[1], nro[0], nro[1],
  389.                                                  configuration.getVersion(), mjdDate));
  390.                     }
  391.                 }
  392.             }

  393.             /** Overwrite a value if it is not set or if we are in a bulletinB.
  394.              * @param oldValue old value to overwrite (may be NaN)
  395.              * @param factor multiplicative factor to apply to raw read data
  396.              * @return a new value
  397.              */
  398.             private double overwrite(final double oldValue, final double factor) {
  399.                 if (buffer.length() == 0) {
  400.                     // there is nothing to overwrite with
  401.                     return oldValue;
  402.                 } else if (inBulletinA && (!Double.isNaN(oldValue))) {
  403.                     // the value is already set and bulletin A values have a low priority
  404.                     return oldValue;
  405.                 } else {
  406.                     // either the value is not set or it is a high priority bulletin B value
  407.                     return Double.parseDouble(buffer.toString()) * factor;
  408.                 }
  409.             }

  410.             /** Check if the year, month, day date and MJD date are consistent.
  411.              */
  412.             private void checkDates() {
  413.                 if (new DateComponents(year, month, day).getMJD() != mjd) {
  414.                     throw new OrekitException(OrekitMessages.INCONSISTENT_DATES_IN_IERS_FILE,
  415.                                               name, year, month, day, mjd);
  416.                 }
  417.             }

  418.         }

  419.     }

  420.     /** Enumerate for data file content. */
  421.     private enum DataFileContent {

  422.         /** Unknown content. */
  423.         UNKNOWN,

  424.         /** Daily data. */
  425.         DAILY,

  426.         /** Final data. */
  427.         FINAL

  428.     }

  429. }