XmlRemapperIO.java

/*
** Module   : XmlRemapperIO.java
** Abstract : Read/write RamRemapper data to/from XML.
**
** Copyright (c) 2005-2025, Golden Code Development Corporation.
**
** -#- -I- --Date-- --JPRM-- ----------------Description-----------------
** 001 SIY 20050407   @21038 Created initial version, extracted
**                           from XmlRemapper.
** 002 ECF 20050421   @20805 Import p2j.xml package to use XmlHelper.
** 003 SIY 20050516   @21207 Updated documentation.
** 004 NVS 20060720   @28109 Any problem with reading from the directory
**                           XML throws a comprehensive exception so that
**                           the problem can be tracked down to a specific
**                           tree node.
** 005 GES 20080318   @37640 Switched from writer to stream to avoid
**                           unwanted character conversion when the
**                           default character set is not 8-bit ASCII.
** 006 GES 20090515   @42209 Imports change.
** 007 SIY 20091007   @44124 Replaced Vector with ArrayList.
** 008 SP  20250416          Code formatting and javadoc fixes.
*/

/*
** 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.directory;

import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

import com.goldencode.p2j.*;
import com.goldencode.util.*;

/**
 * This class perform input/output of the directory tree stored in
 * <code>RamRemapper</code> and derived classes from/to backing XML file.
 * 
 * @author  SIY
 * @version 1.0
 */
class XmlRemapperIO
{
   /** XML attribute name for the node object class name */
   private static final String ATTR_NODE_CLASS = "class";

   /** XML attribute name for the node name */
   private static final String ATTR_NODE_NAME = "name";

   /** XML attribute name for the node attribute name */
   private static final String ATTR_NODEATTR_NAME = "name";

   /** XML attribute name for the node attribute value */
   private static final String ATTR_NODEATTR_VALUE = "value";

   /** XML tag for the node element */
   private static final String ELEM_TAG_NODE = "node";

   /** XML tag for the node attribute element */
   private static final String ELEM_TAG_NODEATTR = "node-attribute";

   /** XML tag for the root element */
   private static final String ELEM_TAG_ROOT = "remapper-storage";

   /** XML document */
   private Document dom;
   
   /**
    * An instance of the <code>RamRemapper</code> used to retrieve object
    * classes.
    */
   private RamRemapper remapper;

   /** XML document processor */
   private final XmlProcessor processor;
   
   /**
    * Construct an instance of the <code>XmlRemapperIO</code>.
    * 
    * @param   remapper
    *          An instance of the <code>RamRemapper</code> which will be
    *          later saved or restored.
    * @param   processor
    *          Optional XML processing class.
    */
   XmlRemapperIO(RamRemapper remapper, XmlProcessor processor)
   {
      this.remapper = remapper;
      this.processor = processor;
      dom = null;
   }

   /**
    * Load tree from the XML document.
    * 
    * @param   in
    *          <code>InputStream</code> from which XML document will be
    *          read.
    *
    * @throws  Exception
    *          Various exceptions are forwarded from <code>XmlHelper</code>
    *          or thrown in case of errors.
    */
   void load(InputStream in)
   throws Exception
   {
      dom = XmlHelper.parse(in);

      Element elem = dom.getDocumentElement();

      Node rootNode = elem.getFirstChild();

      // find the first child that has a tagName "node"
      while (rootNode != null && !rootNode.getNodeName().equals(ELEM_TAG_NODE))
      {
         rootNode = rootNode.getNextSibling();
      }

      RamNode root = readNode(rootNode);
      if (root == null)
      {
         throw new MissingDataException("No valid root element");
      }
      else
      {
         if (processor != null)
         {
            processor.postprocess(dom);
         }
      }

      remapper.setRoot(root);
   }
   
   /**
    * Store tree into stream in XML file.
    * 
    * @param   out
    *          OutputStream which will be used to store XML.
    *
    * @throws  ParserConfigurationException
    *          Forwarded from XmlHelper.
    * @throws  IOException
    *          Forwarded from XmlHelper.
    */
   void save(OutputStream out)
   throws ParserConfigurationException,
      IOException
   {
      dom = XmlHelper.newDocument();

      //Add comments
      Comment comment;
      comment = dom.createComment("XmlRemapper storage");
      dom.appendChild(comment);

      comment = dom.createComment("Saved " + (new Date()));
      dom.appendChild(comment);

      Element elem = dom.createElement(ELEM_TAG_ROOT);
      dom.appendChild(elem);

      writeNode(remapper.getRoot(), elem);

      if (processor != null)
      {
         processor.preprocess(dom, elem);
      }

      XmlHelper.write(dom, out);
   }

   /**
    * Read one node from the XML document.
    * 
    * @param   node
    *          Node instance to read data from.
    *
    * @return  Instance of <code>RamNode</code> or <code>null</code> if
    *          something went wrong.
    */
   private RamNode readNode(Node node)
   {
      if (node == null)
      {
         return null;
      }

      Element elem = (Element)node;

      String nodeClass = elem.getAttribute(ATTR_NODE_CLASS);
      String nodeName = elem.getAttribute(ATTR_NODE_NAME);

      if (nodeClass == null)
      {
         throw new RuntimeException("node class not specified for name '" + nodeName + "'");
      }
      if (nodeName == null)
      {
         throw new RuntimeException("node name not specified for class '" + nodeClass + "'");
      }

      NodeList l = node.getChildNodes();
      int i;

      //First pass, construct attribute list
      List<String> names = new ArrayList<>();
      List<String> values = new ArrayList<>();

      for (i = 0; i < l.getLength(); i++)
      {
         if (l.item(i).getNodeName().equals(ELEM_TAG_NODEATTR))
         {
            elem = (Element)l.item(i);

            String strName = elem.getAttribute(ATTR_NODEATTR_NAME);
            String strValue = elem.getAttribute(ATTR_NODEATTR_VALUE);

            if (strName == null)
            {
               throw new RuntimeException("attribute name not specified for " + "class '" +
                                          nodeClass + "' node '" + nodeName + "'");
            }
            if (strValue == null)
            {
               throw new RuntimeException("attribute value not specified for " + "class '" + nodeClass +
                                          "' node '" + nodeName + "' attribute '" + strName + "'");
            }

            names.add(strName);
            values.add(strValue);
         }
      }

      RamNode ramNode;

      //Restore container in the root
      ramNode = new RamNode(remapper.getObjClass(nodeClass), nodeName);

      for (i = 0; i < names.size(); i++)
      {
         String attrName = names.get(i);
         String attrValue = values.get(i);

         boolean rc = ramNode.addStringAttributeValue(attrName, attrValue);
         if (!rc)
         {
            throw new RuntimeException("wrong attribute '" + attrName + "' in" + " class '" +
                                       nodeClass + "' node '" + nodeName + "'");
         }
      }
      if (!ramNode.isValid())
      {
         throw new RuntimeException("validation failed for class '" +
                                    nodeClass + "' node '" + nodeName + "'");
      }

      //Second pass, rebuild child nodes
      for (i = 0; i < l.getLength(); i++)
      {
         if (l.item(i).getNodeName().equals(ELEM_TAG_NODE))
         {
            RamNode rn = null;
            
            try
            {
               rn = readNode(l.item(i));
            }
            catch (RuntimeException rte)
            {
               throw new RuntimeException("class '" + nodeClass + "' name '" + nodeName + "'", rte);
            }
            if (!ramNode.addChild(rn))
            {
               throw new RuntimeException("class '" + nodeClass + "' name '" +
                                          nodeName + "' failed to add " + "child");
            }
         }
      }
      return ramNode;
   }

   /**
    * Create and write one node into document. Call itself recursively for all
    * child nodes.
    * 
    * @param   ramNode
    *          Directory tree node information about which should be written.
    * @param   parent
    *          Parent Document node which will hold information about new
    *          node.
    */
   private void writeNode(RamNode ramNode, Node parent)
   {
      Element elem = dom.createElement(ELEM_TAG_NODE);

      //Node class and name
      elem.setAttribute(ATTR_NODE_CLASS, ramNode.getNodeClass().getName());
      elem.setAttribute(ATTR_NODE_NAME, ramNode.getName());

      parent.appendChild(elem);

      //Node attributes.
      Attribute[] attr = ramNode.getAttributes();
      if (attr != null)
      {
         for (int i = 0; i < attr.length; i++)
         {
            String[] values = attr[i].getValues();
            if (values == null)
            {
               continue;
            }

            for (int j = 0; j < values.length; j++)
            {
               Element nodeAttr = dom.createElement(ELEM_TAG_NODEATTR);

               nodeAttr.setAttribute(ATTR_NODEATTR_NAME, attr[i].getName());
               nodeAttr.setAttribute(ATTR_NODEATTR_VALUE, values[j]);

               elem.appendChild(nodeAttr);
            }
         }
      }

      RamNode[] list = ramNode.getChildList();
      if (list != null)
      {
         for (int i = 0; i < list.length; i++)
         {
            writeNode(list[i], elem);
         }
      }
   }
}