package com.dbxml.db.common.adapters;

/*
 * dbXML - Native XML Database
 * Copyright (C) 1999-2004  The dbXML Group, L.L.C.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * $Id: XMLSerializableAdapter.java,v 1.3 2004/02/12 00:17:56 bradford Exp $
 */

import com.dbxml.db.core.ClassResolver;
import com.dbxml.db.core.Collection;
import com.dbxml.db.core.DBException;
import com.dbxml.db.core.FaultCodes;
import com.dbxml.db.core.adapter.SimpleAdapter;
import com.dbxml.db.core.data.Key;
import com.dbxml.db.core.transaction.Transaction;
import com.dbxml.xml.XMLSerializable;
import com.dbxml.xml.dom.DOMHelper;
import com.dbxml.xml.dtsm.DTSMException;
import com.dbxml.xml.dtsm.DTSMHelper;
import com.dbxml.xml.dtsm.DocumentTable;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;

/**
 * XMLSerializableAdapter adapts a dbXML Collection to support the management
 * of dbXML XMLSerializable implementations.
 */

public final class XMLSerializableAdapter extends SimpleAdapter {
   private static final String CLASSNAME = "dbxml-class";

   public XMLSerializableAdapter(Collection col) {
      super(col);
   }

   private void putObject(Transaction tx, Object key, XMLSerializable obj) throws DBException {
      Document doc = DOMHelper.newDocument();
      ProcessingInstruction pi = doc.createProcessingInstruction(CLASSNAME, obj.getClass().getName());
      doc.appendChild(pi);
      Node node = obj.streamToXML(doc);
      doc.appendChild(node);

      DocumentTable dt;
      try {
         dt = DTSMHelper.documentToTable(doc, col.getSymbols());
      }
      catch ( DTSMException e ) {
         throw new DBException(FaultCodes.COL_CANNOT_STORE, "Error storing object '" + key + "'", e);
      }

      col.setDocument(tx, key, dt);
   }

   /**
    * setObject sets an XMLSerializable object in the Collection based on the
    * provided Key.  dbXML takes care of associating the implementation class
    * with the XMLSerializable object.
    *
    * @param tx The controlling Transaction
    * @param key The Key to use
    * @param obj The Object to set
    * @throws DBException If a Database Exception occurs
    */
   public void setObject(Transaction tx, Object key, XMLSerializable obj) throws DBException {
      putObject(tx, key, obj);
   }

   /**
    * insertObject inserts an XMLSerializable object into the Collection and
    * returns a newly generated Key.  dbXML takes care of associating the
    * implementation class with the XMLSerializable object.
    *
    * @param tx The controlling Transaction
    * @param obj The Object to insert
    * @return The new Object Identifier
    * @throws DBException If a Database Exception occurs
    */
   public Key insertObject(Transaction tx, XMLSerializable obj) throws DBException {
      Key key = col.createNewOID();
      putObject(tx, key, obj);
      return key;
   }

   /**
    * insertObject inserts an XMLSerializable object into the Collection based
    * on the specified Key.  dbXML takes care of associating the
    * implementation class with the XMLSerializable object.
    *
    * @param tx The controlling Transaction
    * @param key The Key to use
    * @param obj The Object to insert
    * @throws DBException If a Database Exception occurs
    */
   public void insertObject(Transaction tx, Object key, XMLSerializable obj) throws DBException {
      putObject(tx, key, obj);
   }

   /**
    * getObject instantiates and returns an XMLSerializable object based on the
    * provided Key.  dbXML takes care of instantiating the correct class, but
    * only if a class was registered with the Document in the first place.
    *
    * @param tx The controlling Transaction
    * @param key The Document Key
    * @return an Castable XMLSerializable Instance
    * @throws DBException If a Database Exception occurs
    */
   public XMLSerializable getObject(Transaction tx, Object key) throws DBException {
      Document doc = null;
      try {
         DocumentTable dt = col.getDocument(tx, key);
         if ( dt != null )
            doc = DTSMHelper.tableToDocument(dt);
      }
      catch ( DTSMException e ) {
         throw new DBException(FaultCodes.COL_CANNOT_RETRIEVE, "Error retrieving object '" + key + "'", e);
      }

      if ( doc != null ) {
         String className = null;
         NodeList childNodes = doc.getChildNodes();
         int size = childNodes.getLength();
         for ( int i = 0; i < size; i++ ) {
            Node n = childNodes.item(i);
            if ( n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE ) {
               ProcessingInstruction pi = (ProcessingInstruction)n;
               if ( pi.getTarget().equals(CLASSNAME) ) {
                  className = pi.getData().trim();
                  break;
               }
            }
         }

         if ( className != null ) {
            try {
               XMLSerializable obj = (XMLSerializable)ClassResolver.get(className).newInstance();
               obj.streamFromXML(doc.getDocumentElement());
               return obj;
            }
            catch ( Exception e ) {
               e.printStackTrace(System.err);
            }
         }
      }

      return null;
   }
}

