package org.dbxml.examples;

/*
 * dbXML Core - Example Code
 *
 * Copyright (c) 1999-2001 The dbXML Group
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 *    The above copyright notice and this permission notice shall be included
 *       in all copies of substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * $Id: APIExample.java,v 1.12 2001/08/08 04:57:00 kstaken Exp $
 */

import org.dbxml.client.xmldb.DatabaseImpl;
import org.dbxml.client.xmldb.services.*;

import org.xmldb.api.base.*;
import org.xmldb.api.modules.*;
import org.xmldb.api.DatabaseManager;

import org.w3c.dom.*;
import org.dbxml.xml.dom.*;

/**
  * This is a simple API example using the XML:DB client API classes. To see how
  * to use the CORBA api look at CorbaAPIExample.
  */
public class APIExample {
   public static void main(String[] args) throws Exception {
      try {
         Database dbxml = new DatabaseImpl();
         DatabaseManager.registerDatabase(dbxml);
         Collection col =
            DatabaseManager.getCollection("xmldb:dbxml:///db/root/ocs");

         col.setProperty("ResourceType", "XMLText");

         // This is a dbXML specific extension for managing the database.
         DatabaseInstanceManager man =
            (DatabaseInstanceManager) col.getService("DatabaseInstanceManager", "1.0");

         System.out.println("Database Name " + man.getDatabaseName());

         // Run the examples
         listCollections(col);

         String oid = insertDocument(col);

         retrieveDocument(col, oid);

         search(col, "/test");

         col.close();
      } catch (XMLDBException e) {
         System.out.println("ERROR : " + e.toString());
         e.printStackTrace(System.out);
      }
   }

   /**
     * Lists all databases and their collections on the server
     */
   public static void listCollections(Collection col) throws Exception {
      // Get a list of databases
      if (col.getChildCollectionCount() > 0) {
         String[] cols = col.listChildCollections();

         int i = 0;
         while (i < cols.length) {
            System.out.println(cols[i] + "\t");
            i++;
         }
      }
   }

   /**
      * Insert a new document into a collection.
      */
   public static String insertDocument(Collection col) throws Exception {
      // Document must be a valid XML document.
      String document = "<?xml version=\"1.0\"?>\n <test>Hello</test>";
      String key = "test";
      try {
         // TODO: need way to create new OID
         Resource resource = col.createResource(key, "XMLResource");
         resource.setContent(document);

         col.storeResource(resource);
      }
      catch ( Exception e ) {
         System.out.println("Error creating document '" + document + "'");
      }

      System.out.println("Document Key: " + key);
      return key;
   }

   /**
     * Retrieve and print a stored document
     */
   public static void retrieveDocument(Collection col, String oid)
         throws Exception {
      System.out.println("Retrieving Document using getResource");

      System.out.println(oid);

      Resource resource = col.getResource(oid);
      System.out.println(resource.getContent());
   }

   /**
     * Search the database.
     */
   public static void search(Collection col, String xpath) throws Exception {
      System.out.println("Retrieving Documents using a query.");

      XPathQueryService service =
         (XPathQueryService) col.getService("XPathQueryService", "1.0");
      ResourceSet resultSet = service.query(xpath);
      ResourceIterator results = resultSet.getIterator();
      
      while (results.hasMoreResources()) {
         Resource res = results.nextResource();
         System.out.println((String) res.getContent());
      }
   }
}

