ジャナ・ビジネス・コンサルティング有限会社トップページへ
/*
 * Berkeley DB XML .NET API
 * 
 * Copyright (C) 2007 Jana Business Consulting Ltd. All rights reserved.
 * 
 * For more information, see http://www.janabiz.com.
 * 
 */

using System;
using JanaBiz.Db;
using JanaBiz.DbXml;
using JanaBiz.DbXml.Exceptions;

public class QueryForMetaData
{
    private static string theContainer = "namespaceExampleData.dbxml";

    // Shows a timestamp for each record that matches the given XPath query.
    // The timestamp is stored as metadata on each document. This metadata was 
    // added to the document when the example data was loaded into the container 
    // using exampleLoadContainer.java. The timestamp represents the time
    // when the document was loaded into the container.
    private static void showTimeStamp(XmlManager mgr, string query,
                                      XmlQueryContext context)
    {
        // Perform a single query against the referenced container using
        // the referenced context. The timestamp metadata attribute is then
        // displayed.
        Console.WriteLine("Exercising query: '" + query + "'.");
        Console.WriteLine("Return to continue: ");
        Console.ReadLine();

        //Perform the query
        XmlResults results = mgr.Query(null, query, context, new XmlDocumentConfig());

        while (results.MoveNext()) {
            using (XmlDocument document = results.Current.ToDocument()) {
                // We return the metadata as a MetaData object
                using (XmlMetaData md = document.GetMetaData("http://dbxmlExamples/timestamp", "timeStamp")) {
                    Console.WriteLine("Document " + document.Name +
                                      " stored on " + md.Value.ToString());
                }
            }
        }

        Console.WriteLine(results.Size + " results returned for query '"
                          + query + "'.");
    }

    public static void Main(string[] args)
    {
        string envdir = parseArguments(args);

        DbEnvironment dbEnv = null;
        XmlManager mgr = null;
        XmlContainer container = null;

        try {
            // Open an environment
            dbEnv = CreateDbEnvironment(envdir);

            // Open an environment and manager
            using (mgr = CreateManager(dbEnv)) {
                // Open a transactional container
                XmlContainerConfig containerconfig = new XmlContainerConfig();
                containerconfig.Transactional = true;
                using (container = mgr.OpenContainer(null, theContainer,
                                                     containerconfig)) {
                    // Create a context and declare the namespaces
                    using (XmlQueryContext context = mgr.CreateQueryContext()) {
                        context.SetNamespace("fruits", "http://groceryItem.dbxml/fruits");
                        context.SetNamespace("vegetables", "http://groceryItem.dbxml/vegetables");
                        context.SetNamespace("desserts", "http://groceryItem.dbxml/desserts");

                        // Show all the vegetables
                        showTimeStamp(mgr, "collection(\"" + theContainer +
                                           "\")/vegetables:item", context);
                    }
                }
            }
        } catch (DbXmlException e) {
            Console.WriteLine("Error performing query against " + theContainer);
            Console.WriteLine(e.ToString());
        } finally {
            if (container != null) {
                container.Close();
            }
            if (mgr != null) {
                mgr.Close();
            }
            if (dbEnv != null) {
                dbEnv.Close();
            }
        }
    }

    public static DbEnvironment CreateDbEnvironment(string envdir)
    {
        DbEnvironmentConfig envconf = new DbEnvironmentConfig();
        envconf.CacheSize = 50*1024;
        envconf.AllowCreate = true;
        envconf.InitializeCache = true;
        envconf.Transactional = true;
        envconf.InitializeLocking = true;
        envconf.InitializeLogging = true;
        envconf.RunRecovery = true;
        envconf.ErrorWriter = Console.Out;
        envconf.ErrorPrefix = "LOG";

        DbEnvironment env = new DbEnvironment(envdir, envconf);

        return env;
    }

    public static XmlManager CreateManager(DbEnvironment env)
    {
        XmlManagerConfig mgrconfig = new XmlManagerConfig();
        mgrconfig.AdoptEnvironment = true;
        try {
            return new XmlManager(env, mgrconfig);
        } catch (Exception e) {
            env.Close();
            throw e;
        }
    }

    private static void Usage()
    {
        Console.WriteLine("This program retrieves DBXML documents and then retrieves the date and time");
        Console.WriteLine("that the document was stored in the container. You should run exampleLoadContainer");
        Console.WriteLine("before running this example. You are only required to pass this command the path");
        Console.WriteLine("location of the database environment that you specified when you loaded the examples");
        Console.WriteLine("data:");
        Console.WriteLine();
        Console.WriteLine("\t-h <dbenv directory>");
        Console.WriteLine("For example:");
        Console.WriteLine("\tqueryForMetaData.exe -h examplesEnvironment");

        Environment.Exit(-1);
    }

    private static string parseArguments(string[] args)
    {
        string envdir = null;
        for (int i = 0; i < args.Length; ++i) {
            string arg = args[i];
            if ((arg.StartsWith("-")
#if WIN32
                 || arg.StartsWith("/")
#endif
                ) && arg.Length > 1) {
                switch (arg[1]) {
                    case 'h':
                        {
                            ++i;
                            if (i >= args.Length) {
                                Console.WriteLine("Invalid option: " + arg);
                                Usage();
                            }
                            envdir = args[i];
                            break;
                        }
                    default:
                        {
                            Console.WriteLine("Unknown option: " + arg);
                            Usage();
                            break;
                        }
                }
            } else {
                Console.WriteLine("Too many arguments: " + arg);
                Usage();
            }
        }
        if (envdir == null) {
            Console.WriteLine("Environment directory not found.");
            Usage();
        }
        return envdir;
    }
}