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: CorbaAPIExample.java,v 1.12 2001/08/08 04:57:00 kstaken Exp $
 */

import org.dbxml.core.corba.*;
import org.dbxml.core.corba.db.Collection;
import org.dbxml.core.corba.db.*;
import org.dbxml.xml.TextWriter;

import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

import org.w3c.dom.*;

import java.util.*;
import java.io.*;
import java.net.*;

public class CorbaAPIExample {

   private static final byte[] EmptyBytes = new byte[0];
   
   // Default ORB class. This is used to override the JDKs built in CORBA ORB.
   static public final String DEFAULT_ORB_CLASS = "jacorb.orb.ORB";
   // Default ORBSingleton class. This is used to override the JDKs built in CORBA ORB
   static public final String DEFAULT_ORB_SINGLETON_CLASS = "jacorb.orb.ORBSingleton";
   // Property name to use to set the naming service up for resolve_initial_refs
   static public final String DEFAULT_ORB_NAMING_PROP_VALUE = "InitRef.NameService";
   //  Default location where the Name service IOR can be located.
   static public final String DEFAULT_NAMING_URI = "http://localhost:4080/NamingService";

   public static void main(String[] args) {
      try {

         // create and initialize the ORB
         Properties orbConf = new Properties();
         // Set the default naming location which is for OpenORB by default.
         orbConf.put(DEFAULT_ORB_NAMING_PROP_VALUE, DEFAULT_NAMING_URI);

         // Also set it up for JacORB 1.1 to make switching easy.
         orbConf.put("jacorb.NameServerURL", DEFAULT_NAMING_URI);

         // Also set it up for JacORB 1.3 to make switching easy.
         orbConf.put("ORBInitRef.NameService", DEFAULT_NAMING_URI);

         orbConf.put("org.omg.CORBA.ORBClass", DEFAULT_ORB_CLASS);
         orbConf.put("org.omg.CORBA.ORBSingletonClass", DEFAULT_ORB_SINGLETON_CLASS);

         // create and initialize the ORB
         ORB orb = ORB.init(new String[0], orbConf);


         // Retrieve the IOR for the naming service
         URL rss = new URL(DEFAULT_NAMING_URI);
         HttpURLConnection conn =
             (HttpURLConnection) rss.openConnection();

         BufferedReader reader = new BufferedReader(
             new InputStreamReader(conn.getInputStream()));

         String ior = reader.readLine();
         org.omg.CORBA.Object objRef = orb.string_to_object(ior);
         NamingContextExt ncRef = NamingContextExtHelper.narrow(objRef);

         // Get the database instance from naming, the path is dbxml/db
         NameComponent root = new NameComponent("dbxml", "");
         NameComponent instance = new NameComponent("db", "");
         NameComponent path[] = {root, instance};
         Database app = DatabaseHelper.narrow(ncRef.resolve(path));

         System.out.println("Instance Name " + app.getName());

         // Run the examples
         listCollections(app);
         String oid = insertDocument(app);
         retrieveDocument(app, oid);
         updateDocument(app);
         //search(app, "/test");

         //app.getDatabaseManager().shutdown();
      } catch (Exception e) {
         System.out.println("ERROR : " + e) ;
         e.printStackTrace(System.out);
      }
   }

   /**
     * Lists all databases and their collections on the server
     */
   public static void listCollections(Database app) throws Exception {
      // Get a list of databases
      String[] topcols = app.listCollections();
      int i = 0;
      while (i < topcols.length) {
         System.out.println(topcols[i] + ":");

         // Get all the collections for this database.
         Collection col = app.getCollection(topcols[i]);
         String [] collections = col.listCollections();
         int j = 0;
         while (j < collections.length) {
            System.out.println("\t" + collections[j]);
            j++;
         }
         col.remove();
         i++;
      }
   }

   /**
      * Insert a new document into a collection.
      */
   public static String insertDocument(Database app) throws Exception {
      // Document must be a valid XML document.
      String document = "<?xml version=\"1.0\"?>\n <test>Hello</test>";

      // The default install includes a test database with an ocs collection
      Collection col = app.getCollection("root/ocs");

      // CORBA requires the document to be an EncodedBuffer
      EncodedBuffer buf = new EncodedBuffer(-1, EmptyBytes, document.getBytes());
      String key = col.insertDocument("testdoc", buf);
      System.out.println("Document Key: " + key);


      col.remove();
      return key;
   }

   /**
     * Updates an existing document using XUpdate
     */
   public static void updateDocument(Database app) throws Exception {
      String commands = "<xupdate:modifications version=\"1.0\" xmlns:xupdate=\"http://www.xmldb.org/xupdate\"><xupdate:remove select=\"/address/first-name\"/></xupdate:modifications>";

      Collection col = app.getCollection("root");

      col.queryDocument("XUpdate", commands, null, "address4", -1);
      System.out.println("Document Updated");

      col.remove();

   }

   /**
      * Retrieve and print a stored document
      */
   public static void retrieveDocument(Database app, String oid)
         throws Exception {
      // The default install includes a test database with an ocs collection
      Collection col = app.getCollection("root/ocs");
      System.out.println(oid);
      EncodedBuffer buffer = col.getDocument(oid, -1);

      // The XML data is stored in buffer.buf
      System.out.println(new String(buffer.buf));

      col.remove();
   }

   /**
     * Search the database.
     */
   public static void search(Database app, String xpath) throws Exception {
      System.out.println("Retrieving Documents using a query.");
      /*Collection col = app.getCollection("root/ocs");
      DocumentSet documents = col.documentQuery(xpath);

      while (documents.hasMoreDocuments()) {
         printDoc(EncodedBufferConverter.convertToDocument(documents.getNextDocument()));
      }

      documents.remove();
      col.remove();*/
   }

   /**
     * Prints a DOM document to System.out
     */
   public static void printDoc(Document doc) throws Exception {
      TextWriter.write(doc, System.out);
      System.out.println("");
   }
}

