SetDocuments.cs sample program

Shows how to add documents to an existing document base.


/**
 * Title: SetDocuments.cs - a sample to add documents to a docbase
 *
 * Description:  This sample shows how to add documents into
 *               a document base.
 *
 * Syntax:       SetDocuments [-r] user=<domain\\user>
 *                                 password=<password>
 *                                 server=<ServerName>
 *                                 docbase=<DocBaseName>
 *                                 path=<Path>
 *
 * Copyright:    Copyright (c) 2003, 2010
 * Company:      Ixiasoft Technologies Inc.
 *
 * @version 2.0
 * Modified:    2010-06-10
 */

using Ixiasoft.TextmlServer45;
using System;
using System.Threading;
using System.Text;
using System.Collections;
using System.IO;

public class SetDocuments
{

    static String TOKEN_USER     = "USER";
    static String TOKEN_PASSWORD = "PASSWORD";
    static String TOKEN_SERVER   = "SERVER";
    static String TOKEN_DOCBASE  = "DOCBASE";
    static String TOKEN_PATH     = "PATH";    // of the documents to insert
    static String TOKEN_RECURSE  = "RECURSE";

    // Valid parameters accepted from command-line
    static String[] validTokens =
        {TOKEN_USER, TOKEN_PASSWORD, TOKEN_SERVER, TOKEN_DOCBASE, TOKEN_PATH};

    // Which parameters must be specified
    static bool[] mandatory =
        { false    , false         , false       ,  true        ,  true     };

    // If run-time parameters are missing or invalid, display Help
    private static void Usage()
    {
        Console.WriteLine
            ("SetDocuments [-r] " +
             "user=<domain\\user> password=<password> server=<server> " +
             "docbase=<DocBaseName> path=<path>");
        Console.WriteLine
            ("\t-r Recurse into any directories in the path");
        Console.WriteLine
            ("\t<domain\\user> Domain and username used to login to server");
        Console.WriteLine
            ("\t<password> Password of the user");
        Console.WriteLine
            ("\t<ServerName> Name of the server hosting an instance " +
             "of TEXTML Server");
        Console.WriteLine
            ("\t<DocBaseName> Name of the target document base");
        Console.WriteLine
            ("\t<path> The path of the documents to be added to docbase");
        Console.WriteLine();
        Console.WriteLine
            ("Press any key to exit");
        Console.ReadKey();

    }

    // Extract run-time parameters from command-line
    private static Hashtable Extract(String[] args)
        {
            Hashtable retval = new Hashtable(10);

            for (int i = 0; i < args.Length; ++i)
            {
                String[] tokens = args[i].Split('=');
                String token = null, value = null;

                if (tokens.Length > 1)
                    token = tokens[0];
                if (tokens.Length > 1)
                    value = tokens[1];

                if (token == null || value == null)
                {
                    retval.Clear();
                    return retval;
                }

                bool found = false;
                for (int j = 0; j < validTokens.Length && !found; ++j)
                {
                    if (validTokens[j].CompareTo(token.ToUpperInvariant()) == 0
                        && !retval.ContainsKey(validTokens[j]))
                    {
                        retval.Add(validTokens[j], value);
                        found = true;
                    }
                }

                if (!found)
                {
                    retval.Clear();
                    return retval;
                }
            }

            for (int i = 0; i < validTokens.Length; ++i)
            {
                if (mandatory[i] && !retval.ContainsKey(validTokens[i]))
                {
                    retval.Clear();
                    return retval;
                }
            }

            return retval;
        }

    // Returns the contents of a file as an array of bytes
    private static char[] ReadFile(String file)
    {
        System.IO.StreamReader f = new System.IO.StreamReader(file);
        char[] retval = new char[f.BaseStream.Length];

        try
        {
            f.Read(retval,0,(int)f.BaseStream.Length);
        }
        finally
        {
            f.Close();
        }

        return retval;
    }

    // Add all documents found in the source path to the target docbase
    private static void Process(String SourcePath,
                                IxiaDocumentServices ds, // target docbase
                                bool recurse)
    {
        try
        {

            // Create an array of File objects, one for each file/directory
            // stored in the source directory
            String[] files = System.IO.Directory.GetFiles(SourcePath);

            // Create an ArrayList structure.
            // Eventually, there will be one element for
            // each file/directory
            ArrayList documents = new ArrayList(0);

            // For each file/directory...
            for (int i = 0; i < files.Length; ++i)
            {
                // If it is a directory, and user wants recursion, then recurse
                if (File.GetAttributes(files[i]) == FileAttributes.Directory)
                {
                    if (recurse)
                        Process(files[i], ds, true);
                }
                else
                {
                    // It is a file. Create a Document objectfor it.
                    IxiaDocument document = IxiaDocument.getInstance();
                    document.Name = System.IO.Path.GetFileName(files[i]);

                    // Let's assume that all files in the directory are
                    // XML files.
                    document.MimeType = "text/xml";
                    document.Content = IxiaDocument.MakeContentFromFile
                        (new System.IO.FileStream(files[i],FileMode.Open));

                    // Add the document to the ArrayList of documents
                    documents.Add(document);
                }
            }

            // Create docList,
            // an array of documents of the same size as the ArrayList
            IxiaDocument[] docList = new IxiaDocument[documents.Count];
            documents.CopyTo(docList);

            Console.WriteLine("Adding " + docList.Length + " documents from " +
                              System.IO.Path.GetFullPath(SourcePath));

            // Add the documents to the docbase.
            // Index the documents. (Only XML files are indexable.)
            // If a document with the same name already exists in the docbase,
            //     then replace the old document with the new one.
            // The documents are all of type "user document" (i.e., they are
            //     not system documents).

            IxiaTextmlServerError[] err =
                ds.SetDocuments(docList,
                                TextmlConstants.TEXTML_ADD_DOCUMENT |
                                TextmlConstants.TEXTML_REPLACE_DOCUMENT |
                                TextmlConstants.TEXTML_INDEX_DOCUMENT,
                                TextmlDocumentType.TextmlDocument);

            // Process the errors, if any
            int countError = 0;
            if (err != null)
            {
                for (int i = 0; i < err.Length; ++i)
                {
                    if (err[i] != null)
                    {
                        ++countError;
                        if (countError == 1)
                        {
                           Console.WriteLine("Error = " + err[i].Message);
                        }
                    }
                }
            }

            Console.WriteLine("End of adding the documents.");
            Console.WriteLine("Error count = " + countError);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }

  // main routine
    static void Main(string[] args)
    {
        String user = "";

        // Parse the command line

        Hashtable map = Extract(args);

        // Validate the parameters

        if (map.Count == 0)
        {
            Usage();
            return;
        }

        if (map.ContainsKey(TOKEN_USER))
            user = (String)map[TOKEN_USER];

        if (user.IndexOf("\\") == -1)
        {
            Usage();
            return;
        }

        try
        {
            // Get the ClientServices object
            IxiaClientServices cs =
                Ixiasoft.TextmlServer45.ClientServicesFactory.getInstance();

            // Extract domain (or machine name) from user
            String domain = user.Substring(0, user.IndexOf("\\"));
            String userName = user.Substring(user.IndexOf("\\") + 1);

            // Prepare to login to the TEXTML Server instance
            cs.Login(domain, userName, (String)map[TOKEN_PASSWORD]);

            try
            {
                // Get the ServerServices for the specified server
                IxiaServerServices ss =
                    cs.ConnectServer((String) map[TOKEN_SERVER]);
                try
                {
                    // Then, get the DocbaseServices for the specified docbase
                    // on that server
                    IxiaDocBaseServices docbase =
                        ss.ConnectDocBase((String) map[TOKEN_DOCBASE]);
                    try
                    {
                        // Then, get the DocumentServices for the docbase
                        IxiaDocumentServices ds = docbase.DocumentServices;
                        try
                        {
                            // we're now ready to add the documents
                            // into the docbase

                            if (!File.Exists((String)map[TOKEN_PATH]) ||
                                File.GetAttributes((String)map[TOKEN_PATH]) !=
                                    FileAttributes.Directory  )
                            {
                                System.Console.Error.WriteLine
                                    ((String)map[TOKEN_PATH] +
                                     " is not a valid directory.");
                               // return;
                            }

                            // Add the files in rootDir to docbase ds.
                            // Recurse any directories in TOKEN_PATH
                            // only if the user asked for it
                            Process((String)map[TOKEN_PATH], ds,
                                    map.ContainsKey(TOKEN_RECURSE));
                         }
                         finally
                         {
                            ds.Release(); // Tidy up before you exit
                         }
                     }
                     finally
                     {
                        docbase.Release();
                     }
                 }
                 finally
                 {
                    ss.Release();
                 }
            }
            finally
            {
                // And don't forget to logout
                cs.Logout();
                Console.WriteLine();
                Console.WriteLine
                    ("Press any key to exit");
                Console.ReadKey();

            }
        }
        catch (Exception e)
        {
           Console.WriteLine
               ("Exception thrown in SetDocuments.main: " + e);
           Console.WriteLine
               (e.StackTrace);
           Console.WriteLine();
           Console.WriteLine
               ("Exception termination. Press any key to exit");
           Console.ReadKey();

        }

    }
}