# LookAheadXmlStreamReader.java

    /*
    ** Module   : LookAheadXmlStreamReader.java
    ** Abstract : XMLStreamReader with 'peek' operation.
    **
    ** Copyright (c) 2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 IAS 20230426 Created initial version.
    */

    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.persist.serial;

    import java.io.*;
    import java.nio.*;
    import java.util.*;
    import javax.xml.namespace.*;
    import javax.xml.stream.*;
    import org.apache.commons.io.input.*;

    /** XMLStreamReader with 'peek' operation. */
    public class LookAheadXmlStreamReader
    implements XMLStreamReader
    {
       /** Actual reader */
       private final XMLStreamReader delegate;

       /** Flag indicating that reader is used not for inferring DATASET/TEMP-TABLE structure */
       private boolean notForInfer = true;

       /** Last result of 'peek' */
       private OptionalInt next = OptionalInt.empty();

       /** Last saved local name */
       private Optional<String> localName = Optional.empty();

       /** Last saved list of attributes' names */
       private List<QName> attrNames = new ArrayList<>();

       /** Last saved list of attributes' local names */
       private List<String> attrLocalNames = new ArrayList<>();

       /** Last saved list of attributes' names */
       private List<String> attrValues = new ArrayList<>();

       /** Last saved namespace */
       private String nsUri = null;

       /** Last saved namespace prefix */
       private String nsPrefix = null;

       /**
        * Factory method. Creates and returns a {@code LookAheadXmlStreamReader} which adds 'peek()' feature to
        * the {@code delegate} reader.
        *
        * @param   delegate
        *          The underlying reader instance.
        *
        * @return  The wrapper instance.
        */
       public static LookAheadXmlStreamReader wrap(XMLStreamReader delegate)
       {
          return new LookAheadXmlStreamReader(delegate);
       }

       /**
        * Private c'tor used by the static factory method.
        *
        * @param   delegate
        *          The underlying reader instance.
        */
       private LookAheadXmlStreamReader(XMLStreamReader delegate)
       {
          this.delegate = delegate;
       }

       /**
        * Set the flag indicating the reader is used for inferring DATASET/TEMP-TABLE structure.
        *
        * @param   forInfer
        *          <code>true</true> if the reader is used for inferring DATASET/TEMP-TABLE structure.
        *
        * @return  self object. Allows chained calls.
        */
       public LookAheadXmlStreamReader inferMode(boolean forInfer)
       {
          this.notForInfer = !forInfer;
          if (!forInfer)
          {
             localName = Optional.empty();
          }
          else
          {
             saveAttr();
          }

          return this;
       }

       /**
        * Save attributes of the current element
        */
       public void saveAttr()
       {
          if (notForInfer || delegate.getEventType() != XMLStreamReader.START_ELEMENT)
          {
             return;
          }
          localName = Optional.of(delegate.getLocalName());
          nsPrefix = delegate.getPrefix();
          nsUri = delegate.getNamespaceURI();
          int attrs = delegate.getAttributeCount();
          attrLocalNames.clear();
          attrNames.clear();
          attrValues.clear();
          for (int i = 0; i < attrs; i++)
          {
             attrLocalNames.add(delegate.getAttributeLocalName(i));
             attrNames.add(delegate.getAttributeName(i));
             attrValues.add(delegate.getAttributeValue(i));
          }
       }

       /**
        * Peek the next parsing event.
        *
        * @return  the next parsing event.
        *
        * @throws  XMLStreamException
        *          if there is an error processing the underlying XML source.
        */
       public int peek()
       throws XMLStreamException
       {
          if (!next.isPresent())
          {
             next = OptionalInt.of(delegate.next());
          }
          return next.getAsInt();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#close()
        */
       public void close()
       throws XMLStreamException
       {
          delegate.close();
       }

       /**
        * Returns the numbers of saved attributes or calls delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getAttributeCount()
        *
        */
       public int getAttributeCount()
       {
          return localName.isPresent() ? attrNames.size() : delegate.getAttributeCount();
       }

       /**
        * Returns the qname of the saved attribute at the provided index or calls delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getAttributeLocalName(int)
        */
       public String getAttributeLocalName(int index)
       {
          return localName.isPresent() ? attrLocalNames.get(index) : delegate.getAttributeLocalName(index);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getAttributeName(int)
        */
       public QName getAttributeName(int index)
       {
          return localName.isPresent() ? attrNames.get(index) : delegate.getAttributeName(index);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getAttributeNamespace(int)
        */
       public String getAttributeNamespace(int index)
       {
          return delegate.getAttributeNamespace(index);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getAttributePrefix(int)
        */
       public String getAttributePrefix(int index)
       {
          return delegate.getAttributePrefix(index);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getAttributeType(int)
        */
       public String getAttributeType(int index)
       {
          return delegate.getAttributeType(index);
       }

       /**
        * Returns the value of the saved attribute at the index or call delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getAttributeValue(int)
        */
       public String getAttributeValue(int index)
       {
          return localName.isPresent() ? attrValues.get(index) : delegate.getAttributeValue(index);
       }

       /**
        * Returns the normalized attribute value of the saved attribute with the namespace and localName
        * or calls delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getAttributeValue(java.lang.String, java.lang.String)
        */
       public String getAttributeValue(String namespaceURI, String localName)
       {
          return delegate.getAttributeValue(namespaceURI, localName);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getCharacterEncodingScheme()
        */
       public String getCharacterEncodingScheme()
       {
          return delegate.getCharacterEncodingScheme();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getElementText()
        */
       public String getElementText()
       throws XMLStreamException
       {
          return delegate.getElementText();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getEncoding()
        */
       public String getEncoding()
       {
          return delegate.getEncoding();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getEventType()
        */
       public int getEventType()
       {
          return delegate.getEventType();
       }

       /**
        * Returns the (local) name of the saved event or call delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getLocalName()
        */
       public String getLocalName()
       {
          saveAttr();
          return localName.isPresent() ? localName.get() : delegate.getLocalName();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getLocation()
        */
       public Location getLocation()
       {
          return delegate.getLocation();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getName()
        */
       public QName getName()
       {
          return delegate.getName();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getNamespaceContext()
        */
       public NamespaceContext getNamespaceContext()
       {
          return delegate.getNamespaceContext();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getNamespaceCount()
        */
       public int getNamespaceCount()
       {
          return delegate.getNamespaceCount();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getNamespacePrefix(int)
        */
       public String getNamespacePrefix(int index)
       {
          return delegate.getNamespacePrefix(index);
       }

       /**
        * Returns the URI of the prefix or the default namespace of the saved event or call delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getNamespaceURI()
        */
       public String getNamespaceURI()
       {
          return localName.isPresent() ? nsUri : delegate.getNamespaceURI();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getNamespaceURI(int)
        */
       public String getNamespaceURI(int index)
       {
          return delegate.getNamespaceURI(index);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getNamespaceURI(java.lang.String)
        */
       public String getNamespaceURI(String prefix)
       {
          return delegate.getNamespaceURI(prefix);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getPIData()
        */
       public String getPIData()
       {
          return delegate.getPIData();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getPITarget()
        */
       public String getPITarget()
       {
          return delegate.getPITarget();
       }

       /**
        * Returns the prefix of the saved event or calls delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#getPrefix()
        */
       public String getPrefix()
       {
          return localName.isPresent() ? nsPrefix : delegate.getPrefix();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getProperty(java.lang.String)
        */
       public Object getProperty(String name)
       throws IllegalArgumentException
       {
          return delegate.getProperty(name);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getText()
        */
       public String getText()
       {
          return delegate.getText();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getTextCharacters()
        */
       public char[] getTextCharacters()
       {
          return delegate.getTextCharacters();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getTextCharacters(int, char[], int, int)
        */
       public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length)
       throws XMLStreamException
       {
          return delegate.getTextCharacters(sourceStart, target, targetStart, length);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getTextLength()
        */
       public int getTextLength()
       {
          return delegate.getTextLength();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getTextStart()
        */
       public int getTextStart()
       {
          return delegate.getTextStart();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#getVersion()
        */
       public String getVersion()
       {
          return delegate.getVersion();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#hasName()
        */
       public boolean hasName()
       {
          return delegate.hasName();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#hasNext()
        */
       public boolean hasNext()
       throws XMLStreamException
       {
          return delegate.hasNext();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#hasText()
        */
       public boolean hasText()
       {
          return delegate.hasText();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#isAttributeSpecified(int)
        */
       public boolean isAttributeSpecified(int index)
       {
          return delegate.isAttributeSpecified(index);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#isCharacters()
        */
       public boolean isCharacters()
       {
          return delegate.isCharacters();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#isEndElement()
        */
       public boolean isEndElement()
       {
          return delegate.isEndElement();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#isStandalone()
        */
       public boolean isStandalone()
       {
          return delegate.isStandalone();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#isStartElement()
        */
       public boolean isStartElement()
       {
          return delegate.isStartElement();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#isWhiteSpace()
        */
       public boolean isWhiteSpace()
       {
          return delegate.isWhiteSpace();
       }

       /**
        * Get saved parsing event or calls delegate.
        *
        * @see javax.xml.stream.XMLStreamReader#next()
        */
       public int next()
       throws XMLStreamException
       {
          try
          {
             return next.isPresent() ? next.getAsInt() : delegate.next();
          }
          finally
          {
             next = OptionalInt.empty();
          }
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#nextTag()
        */
       public int nextTag()
       throws XMLStreamException
       {
          return delegate.nextTag();
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#require(int, java.lang.String, java.lang.String)
        */
       public void require(int type, String namespaceURI, String localName)
       throws XMLStreamException
       {
          delegate.require(type, namespaceURI, localName);
       }

       /**
        * @see javax.xml.stream.XMLStreamReader#standaloneSet()
        */
       public boolean standaloneSet()
       {
          return delegate.standaloneSet();
       }
    }