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

  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.InputStreamReader;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.SortedSet;

  24. import javax.xml.parsers.ParserConfigurationException;
  25. import javax.xml.parsers.SAXParserFactory;

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

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

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

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

  62.     /** Regular expression for supported files names. */
  63.     private final String supportedNames;

  64.     /** Build a loader for IERS XML EOP files.
  65.      * @param supportedNames regular expression for supported files names
  66.      */
  67.     RapidDataAndPredictionXMLLoader(final String supportedNames) {
  68.         this.supportedNames = supportedNames;
  69.     }

  70.     /** {@inheritDoc} */
  71.     public void fillHistory(final IERSConventions.NutationCorrectionConverter converter,
  72.                             final SortedSet<EOPEntry> history)
  73.         throws OrekitException {
  74.         final Parser parser = new Parser(converter);
  75.         DataProvidersManager.getInstance().feed(supportedNames, parser);
  76.         history.addAll(parser.history);
  77.     }

  78.     /** Internal class performing the parsing. */
  79.     private static class Parser implements DataLoader {

  80.         /** Converter for nutation corrections. */
  81.         private final IERSConventions.NutationCorrectionConverter converter;

  82.         /** Configuration for ITRF versions. */
  83.         private final ITRFVersionLoader itrfVersionLoader;

  84.         /** History entries. */
  85.         private final List<EOPEntry> history;

  86.         /** Simple constructor.
  87.          * @param converter converter to use
  88.          * @exception OrekitException if ITRF version loader cannot be parsed
  89.          */
  90.         Parser(final IERSConventions.NutationCorrectionConverter converter)
  91.             throws OrekitException {
  92.             this.converter         = converter;
  93.             this.itrfVersionLoader = new ITRFVersionLoader(ITRFVersionLoader.SUPPORTED_NAMES);
  94.             this.history           = new ArrayList<EOPEntry>();
  95.         }

  96.         /** {@inheritDoc} */
  97.         public boolean stillAcceptsData() {
  98.             return true;
  99.         }

  100.         /** {@inheritDoc} */
  101.         public void loadData(final InputStream input, final String name)
  102.             throws IOException, OrekitException {
  103.             try {
  104.                 // set up a reader for line-oriented bulletin B files
  105.                 final XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
  106.                 reader.setContentHandler(new EOPContentHandler(name));
  107.                 // disable external entities
  108.                 reader.setEntityResolver((publicId, systemId) -> new InputSource());

  109.                 // read all file, ignoring header
  110.                 reader.parse(new InputSource(new InputStreamReader(input, "UTF-8")));

  111.             } catch (SAXException se) {
  112.                 if ((se.getCause() != null) && (se.getCause() instanceof OrekitException)) {
  113.                     throw (OrekitException) se.getCause();
  114.                 }
  115.                 throw new OrekitException(se, LocalizedCoreFormats.SIMPLE_MESSAGE, se.getMessage());
  116.             } catch (ParserConfigurationException pce) {
  117.                 throw new OrekitException(pce, LocalizedCoreFormats.SIMPLE_MESSAGE, pce.getMessage());
  118.             }
  119.         }

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

  122.             // CHECKSTYLE: stop JavadocVariable check

  123.             // elements and attributes used in both daily and finals data files
  124.             private static final String MJD_ELT           = "MJD";
  125.             private static final String LOD_ELT           = "LOD";
  126.             private static final String X_ELT             = "X";
  127.             private static final String Y_ELT             = "Y";
  128.             private static final String DPSI_ELT          = "dPsi";
  129.             private static final String DEPSILON_ELT      = "dEpsilon";
  130.             private static final String DX_ELT            = "dX";
  131.             private static final String DY_ELT            = "dY";

  132.             // elements and attributes specific to daily data files
  133.             private static final String DATA_EOP_ELT      = "dataEOP";
  134.             private static final String TIME_SERIES_ELT   = "timeSeries";
  135.             private static final String DATE_YEAR_ELT     = "dateYear";
  136.             private static final String DATE_MONTH_ELT    = "dateMonth";
  137.             private static final String DATE_DAY_ELT      = "dateDay";
  138.             private static final String POLE_ELT          = "pole";
  139.             private static final String UT_ELT            = "UT";
  140.             private static final String UT1_U_UTC_ELT     = "UT1_UTC";
  141.             private static final String NUTATION_ELT      = "nutation";
  142.             private static final String SOURCE_ATTR       = "source";
  143.             private static final String BULLETIN_A_SOURCE = "BulletinA";

  144.             // elements and attributes specific to finals data files
  145.             private static final String FINALS_ELT        = "Finals";
  146.             private static final String DATE_ELT          = "date";
  147.             private static final String EOP_SET_ELT       = "EOPSet";
  148.             private static final String BULLETIN_A_ELT    = "bulletinA";
  149.             private static final String UT1_M_UTC_ELT     = "UT1-UTC";

  150.             private boolean inBulletinA;
  151.             private int     year;
  152.             private int     month;
  153.             private int     day;
  154.             private int     mjd;
  155.             private AbsoluteDate mjdDate;
  156.             private double  dtu1;
  157.             private double  lod;
  158.             private double  x;
  159.             private double  y;
  160.             private double  dpsi;
  161.             private double  deps;
  162.             private double  dx;
  163.             private double  dy;

  164.             // CHECKSTYLE: resume JavadocVariable check

  165.             /** File name. */
  166.             private final String name;

  167.             /** Buffer for read characters. */
  168.             private final StringBuffer buffer;

  169.             /** Indicator for daily data XML format or final data XML format. */
  170.             private DataFileContent content;

  171.             /** ITRF version configuration. */
  172.             private ITRFVersionLoader.ITRFVersionConfiguration configuration;

  173.             /** Simple constructor.
  174.              * @param name file name
  175.              */
  176.             EOPContentHandler(final String name) {
  177.                 this.name   = name;
  178.                 this.buffer = new StringBuffer();
  179.             }

  180.             /** {@inheritDoc} */
  181.             @Override
  182.             public void startDocument() {
  183.                 content       = DataFileContent.UNKNOWN;
  184.                 configuration = null;
  185.             }

  186.             /** {@inheritDoc} */
  187.             @Override
  188.             public void characters(final char[] ch, final int start, final int length) {
  189.                 buffer.append(ch, start, length);
  190.             }

  191.             /** {@inheritDoc} */
  192.             @Override
  193.             public void startElement(final String uri, final String localName,
  194.                                      final String qName, final Attributes atts) {

  195.                 // reset the buffer to empty
  196.                 buffer.delete(0, buffer.length());

  197.                 if (content == DataFileContent.UNKNOWN) {
  198.                     // try to identify file content
  199.                     if (qName.equals(TIME_SERIES_ELT)) {
  200.                         // the file contains final data
  201.                         content = DataFileContent.DAILY;
  202.                     } else if (qName.equals(FINALS_ELT)) {
  203.                         // the file contains final data
  204.                         content = DataFileContent.FINAL;
  205.                     }
  206.                 }

  207.                 if (content == DataFileContent.DAILY) {
  208.                     startDailyElement(qName, atts);
  209.                 } else if (content == DataFileContent.FINAL) {
  210.                     startFinalElement(qName, atts);
  211.                 }

  212.             }

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

  228.             /** Handle end of an element in a final data file.
  229.              * @param qName name of the element
  230.              * @param atts element attributes
  231.              */
  232.             private void startFinalElement(final String qName, final Attributes atts) {
  233.                 if (qName.equals(EOP_SET_ELT)) {
  234.                     // reset EOP data
  235.                     resetEOPData();
  236.                 } else if (qName.equals(BULLETIN_A_ELT)) {
  237.                     inBulletinA = true;
  238.                 }
  239.             }

  240.             /** Reset EOP data.
  241.              */
  242.             private void resetEOPData() {
  243.                 inBulletinA = false;
  244.                 year        = -1;
  245.                 month       = -1;
  246.                 day         = -1;
  247.                 mjd         = -1;
  248.                 mjdDate     = null;
  249.                 dtu1        = Double.NaN;
  250.                 lod         = Double.NaN;
  251.                 x           = Double.NaN;
  252.                 y           = Double.NaN;
  253.                 dpsi        = Double.NaN;
  254.                 deps        = Double.NaN;
  255.                 dx          = Double.NaN;
  256.                 dy          = Double.NaN;
  257.             }

  258.             /** {@inheritDoc} */
  259.             @Override
  260.             public void endElement(final String uri, final String localName, final String qName)
  261.                 throws SAXException {
  262.                 try {
  263.                     if (content == DataFileContent.DAILY) {
  264.                         endDailyElement(qName);
  265.                     } else if (content == DataFileContent.FINAL) {
  266.                         endFinalElement(qName);
  267.                     }
  268.                 } catch (OrekitException oe) {
  269.                     throw new SAXException(oe);
  270.                 }
  271.             }

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

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

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

  406.             /** Check if the year, month, day date and MJD date are consistent.
  407.              * @exception OrekitException if dates are not consistent
  408.              */
  409.             private void checkDates() throws OrekitException {
  410.                 if (new DateComponents(year, month, day).getMJD() != mjd) {
  411.                     throw new OrekitException(OrekitMessages.INCONSISTENT_DATES_IN_IERS_FILE,
  412.                                               name, year, month, day, mjd);
  413.                 }
  414.             }

  415.         }

  416.         /** Enumerate for data file content. */
  417.         private enum DataFileContent {

  418.             /** Unknown content. */
  419.             UNKNOWN,

  420.             /** Daily data. */
  421.             DAILY,

  422.             /** Final data. */
  423.             FINAL;

  424.         }

  425.     }

  426. }