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 queryWithContext
{
    
    private static String theContainer = "namespaceExampleData.dbxml";
    private static void usage()
    {
         String usageMessage = "\nThis program illustrates how to query for documents that require namespace\n";
                usageMessage += "usage in the query. 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.queryWithContext -h examplesEnvironment\n";

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

    //Performs a query against a document using an XmlQueryContext.
    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);
       //Iterate over the results with an XmlValue
       XmlValue value = new XmlValue();
       while ( (value = results.next()) != null ) {
            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 use it to 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");

            //Set a variable
            context.setVariableValue("aDessert", new XmlValue("Blueberry Boy Bait"));

            //Perform the queries

            //Find all the Vendor documents in the database. Vendor documents do
            // not use namespaces, so this query returns documents.
            doContextQuery(openedContainer.getContainer(), "/vendor", context);

            //Find the product document for "Lemon Grass". This query returns no documents
            // because a namespace prefix is not identified for the 'item' node.
            doContextQuery(openedContainer.getContainer(), "/item/product[text()=\"Lemon Grass\"]", context);

            //Find the product document for "Lemon Grass" using the namespace prefix 'fruits'. This
            // query successfully returns a document.
            doContextQuery(openedContainer.getContainer(), "/fruits:item/product[text()=\"Lemon Grass\"]", context);

            //Find all the vegetables
            doContextQuery(openedContainer.getContainer(), "/vegetables:item", context);

            //Find the  dessert called Blueberry Boy Bait.
            // Note the use of a variable.
            doContextQuery(openedContainer.getContainer(), "/desserts:item/product[text()=$aDessert]", 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

}
