package com.sleepycat.dbxml.examples.gettingStarted;

import java.io.*;
import com.sleepycat.dbxml.examples.gettingStarted.myDbEnv;
import com.sleepycat.dbxml.examples.gettingStarted.myXmlContainer;

import com.sleepycat.dbxml.*;
import com.sleepycat.db.*;

class queryWithDocumentNames
{
    
    private static String theContainer = "namespaceExampleData.dbxml";
    private static void usage()
    {
         String usageMessage = "\nThis program retrieves DB XML documents using their document names.\n";
                usageMessage += "You should run exampleLoadContainer before running this example.\n";
                usageMessage += "You are only required to pass this command the path location of the database\n";
                usageMessage += "environment that you specified when you loaded the examples data:\n\n";

                usageMessage += "\t-h <dbenv directory>\n";

                usageMessage += "For example:\n";
                usageMessage += "\tjava com.sleepycat.dbxml.examples.gettingStarted.queryWithDocumentNames -h examplesEnvironment\n";

         System.out.println(usageMessage);
         System.exit( -1 );
    }

    //Performs an XPath query against a container using the given context.
    private static void doContextQuery( XmlContainer container, String XPath, XmlQueryContext context ) throws Throwable
    {
       //Perform a single query against the referenced container using
       // the referenced context.
       System.out.println("Exercising query: '" + XPath + "'.");
       System.out.println("Return to continue: ");
       System.in.read();

       //Perform the query
       XmlResults results = container.queryWithXPath(null, XPath, context, 0);
       //We're going to iterate over the results using both an XmlValue and
       // an XmlDocument
       XmlValue value = new XmlValue();
       XmlDocument document = new XmlDocument();
       while (results.next(document, value)) {
            System.out.println("Document name: " + document.getName());
            System.out.println(value.asString(null));
       }
       System.out.println(results.size() + " results returned for query '" + XPath + "'.");
    }


    public static void main(String args[]) throws Throwable
    {

       File path2DbEnv = null;

       for(int i = 0; i < args.length; ++i) 
       {
            if (args[i].startsWith("-")) {
               switch(args[i].charAt(1)) {
                    case 'h':
                         path2DbEnv = new File( args[++i] );
                         break;
                    default:
                    usage();
               }
            } 
       }


       if (path2DbEnv == null || ! path2DbEnv.isDirectory())
       {
            usage();
       }


       myDbEnv theDBEnv = null;
       myXmlContainer openedContainer = null;
       try
       {
            //Open a database environment
            theDBEnv = new myDbEnv(path2DbEnv);
            //Open a container in that environment
            openedContainer = new myXmlContainer(theContainer, theDBEnv);

            //Create a context and declare the namespaces
            XmlQueryContext context = new XmlQueryContext(XmlQueryContext.ResultDocuments, XmlQueryContext.Eager);
            context.setNamespace("fruits", "http://groceryItem.dbxml/fruits");
            context.setNamespace("vegetables", "http://groceryItem.dbxml/vegetables");
            context.setNamespace("desserts", "http://groceryItem.dbxml/desserts");

            //Query for documents using their document names.
            // The name is stored on the root node of the document using the name attribute in the 
            // dbxml namespace. Notice that you do NOT have to declare the dbxml namespace on the 
            // XmlQueryContext used for this query. Also, each document name was set by 
            // exampleLoadContainer when the document was loaded into the XmlContainer.
            doContextQuery(openedContainer.getContainer(), "/*[@dbxml:name='ZuluNut.xml']", context);
            doContextQuery(openedContainer.getContainer(), "//*[@dbxml:name='TrifleOrange.xml']", context);
            doContextQuery(openedContainer.getContainer(), "//*[@dbxml:name='TriCountyProduce.xml']", context);
            doContextQuery(openedContainer.getContainer(), "/fruits:item/product[text()=\"Zulu Nut\"]", context);

       } catch (Exception e) {

            System.err.println("Error performing query against " + theContainer);
            System.err.println("   Message: " + e.getMessage());
            throw e;

       } finally {
            if (openedContainer != null) {
               openedContainer.cleanup();
            }

            if (theDBEnv != null) {
               theDBEnv.cleanup();
            }
       }

    } //end main
}
