AbstractMessageParser.java

  1. /* Copyright 2002-2025 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.files.ccsds.utils.parsing;

  18. import java.io.IOException;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.function.Function;
  25. import org.hipparchus.exception.LocalizedCoreFormats;
  26. import org.orekit.data.DataSource;
  27. import org.orekit.errors.OrekitException;
  28. import org.orekit.errors.OrekitInternalError;
  29. import org.orekit.files.ccsds.utils.FileFormat;
  30. import org.orekit.files.ccsds.utils.lexical.LexicalAnalyzerSelector;
  31. import org.orekit.files.ccsds.utils.lexical.MessageParser;
  32. import org.orekit.files.ccsds.utils.lexical.MessageVersionXmlTokenBuilder;
  33. import org.orekit.files.ccsds.utils.lexical.ParseToken;
  34. import org.orekit.files.ccsds.utils.lexical.TokenType;
  35. import org.orekit.files.ccsds.utils.lexical.XmlTokenBuilder;

  36. /** Parser for CCSDS messages.
  37.  * <p>
  38.  * Note than starting with Orekit 11.0, CCSDS message parsers are
  39.  * mutable objects that gather the data being parsed, until the
  40.  * message is complete and the {@link #parseMessage(org.orekit.data.DataSource)
  41.  * parseMessage} method has returned. This implies that parsers
  42.  * should <em>not</em> be used in a multi-thread context. The recommended
  43.  * way to use parsers is to either dedicate one parser for each message
  44.  * and drop it afterwards, or to use a single-thread loop.
  45.  * </p>
  46.  * @param <T> type of the file
  47.  * @author Luc Maisonobe
  48.  * @since 11.0
  49.  */
  50. public abstract class AbstractMessageParser<T> implements MessageParser<T> {

  51.     /** Comment key.
  52.      * @since 12.0
  53.      */
  54.     private static final String COMMENT = "COMMENT";

  55.     /** Safety limit for loop over processing states. */
  56.     private static final int MAX_LOOP = 100;

  57.     /** Root element for XML files. */
  58.     private final String root;

  59.     /** Key for format version. */
  60.     private final String formatVersionKey;

  61.     /** Filters for parse tokens. */
  62.     private final Function<ParseToken, List<ParseToken>>[] filters;

  63.     /** Anticipated next processing state. */
  64.     private ProcessingState next;

  65.     /** Current processing state. */
  66.     private ProcessingState current;

  67.     /** Fallback processing state. */
  68.     private ProcessingState fallback;

  69.     /** Format of the file ready to be parsed. */
  70.     private FileFormat format;

  71.     /** Flag for XML end tag. */
  72.     private boolean endTagSeen;

  73.     /** Simple constructor.
  74.      * @param root root element for XML files
  75.      * @param formatVersionKey key for format version
  76.      * @param filters filters to apply to parse tokens
  77.      * @since 12.0
  78.      */
  79.     protected AbstractMessageParser(final String root, final String formatVersionKey,
  80.                                     final Function<ParseToken, List<ParseToken>>[] filters) {
  81.         this.root             = root;
  82.         this.formatVersionKey = formatVersionKey;
  83.         this.filters          = filters.clone();
  84.         this.current          = null;
  85.         setFallback(new ErrorState());
  86.     }

  87.     /** Set fallback processing state.
  88.      * <p>
  89.      * The fallback processing state is used if anticipated state fails
  90.      * to parse the token.
  91.      * </p>
  92.      * @param fallback processing state to use if anticipated state does not work
  93.      */
  94.     public void setFallback(final ProcessingState fallback) {
  95.         this.fallback = fallback;
  96.     }

  97.     /** Reset parser to initial state before parsing.
  98.      * @param fileFormat format of the file ready to be parsed
  99.      * @param initialState initial processing state
  100.      */
  101.     protected void reset(final FileFormat fileFormat, final ProcessingState initialState) {
  102.         format     = fileFormat;
  103.         current    = initialState;
  104.         endTagSeen = false;
  105.         anticipateNext(fallback);
  106.     }

  107.     /** Set the flag for XML end tag.
  108.      * @param endTagSeen if true, the XML end tag has been seen
  109.      */
  110.     public void setEndTagSeen(final boolean endTagSeen) {
  111.         this.endTagSeen = endTagSeen;
  112.     }

  113.     /** Check if XML end tag has been seen.
  114.      * @return true if XML end tag has been seen
  115.      */
  116.     public boolean wasEndTagSeen() {
  117.         return endTagSeen;
  118.     }

  119.     /** Get the current processing state.
  120.      * @return current processing state
  121.      */
  122.     public ProcessingState getCurrent() {
  123.         return current;
  124.     }

  125.     /** {@inheritDoc} */
  126.     @Override
  127.     public FileFormat getFileFormat() {
  128.         return format;
  129.     }

  130.     /** {@inheritDoc} */
  131.     @Override
  132.     public T parseMessage(final DataSource source) {
  133.         try {
  134.             return LexicalAnalyzerSelector.select(source).accept(this);
  135.         } catch (IOException ioe) {
  136.             throw new OrekitException(ioe, LocalizedCoreFormats.SIMPLE_MESSAGE,
  137.                                       ioe.getLocalizedMessage());
  138.         }
  139.     }

  140.     /** {@inheritDoc} */
  141.     @Override
  142.     public String getFormatVersionKey() {
  143.         return formatVersionKey;
  144.     }

  145.     /** {@inheritDoc} */
  146.     @Override
  147.     public Map<String, XmlTokenBuilder> getSpecialXmlElementsBuilders() {

  148.         final HashMap<String, XmlTokenBuilder> builders = new HashMap<>();

  149.         if (formatVersionKey != null) {
  150.             // special handling of root tag that contains the format version
  151.             builders.put(root, new MessageVersionXmlTokenBuilder());
  152.         }

  153.         return builders;

  154.     }

  155.     /** Anticipate what next processing state should be.
  156.      * @param anticipated anticipated next processing state
  157.      */
  158.     public void anticipateNext(final ProcessingState anticipated) {
  159.         this.next = anticipated;
  160.     }

  161.     /** {@inheritDoc} */
  162.     @Override
  163.     public void process(final ParseToken token) {

  164.         // loop over the filters
  165.         List<ParseToken> filtered = Collections.singletonList(token);
  166.         for (Function<ParseToken, List<ParseToken>> filter : filters) {
  167.             final ArrayList<ParseToken> newFiltered = new ArrayList<>();
  168.             for (final ParseToken original : filtered) {
  169.                 newFiltered.addAll(filter.apply(original));
  170.             }
  171.             filtered = newFiltered;
  172.         }
  173.         if (filtered.isEmpty()) {
  174.             return;
  175.         }

  176.         int remaining = filtered.size();
  177.         for (final ParseToken filteredToken : filtered) {

  178.             if (filteredToken.getType() == TokenType.ENTRY &&
  179.                 !COMMENT.equals(filteredToken.getName()) &&
  180.                 (filteredToken.getRawContent() == null || filteredToken.getRawContent().isEmpty())) {
  181.                 // value is empty, token is ignored
  182.                 if (--remaining == 0) {
  183.                     // we have processed all filtered tokens
  184.                     return;
  185.                 }
  186.             }
  187.             else {
  188.                 // loop over the various states until one really processes the token
  189.                 for (int i = 0; i < MAX_LOOP; ++i) {
  190.                     if (current.processToken(filteredToken)) {
  191.                         // filtered token was properly processed
  192.                         if (--remaining == 0) {
  193.                             // we have processed all filtered tokens
  194.                             return;
  195.                         }
  196.                         else {
  197.                             // we need to continue processing the remaining filtered tokens
  198.                             break;
  199.                         }
  200.                     }
  201.                     else {
  202.                         // filtered token was not processed by current processing state, switch to next one
  203.                         current = next;
  204.                         next = fallback;
  205.                     }
  206.                 }
  207.             }

  208.         }

  209.         // this should never happen
  210.         throw new OrekitInternalError(null);

  211.     }

  212. }