GetDocument.java sample program

How to retrieve a document by specifying the document name.

package com.ixiasoft.samples;
/**
 * Title: GetDocument.java - a sample to retrieve a document from a docbase
 *
 * Description:  This sample shows how to retrieve a document into
 *               a document base *when you know the name of the document*.
 *
 *               It also shows how to handle errors that might occur when
 *               you attempt to retrieve the document.
 *
 * Syntax:       GetDocument user=<domain\\user>
 *                           password=<password>
 *                           server=<ServerName>
 *                           docbase=<DocBaseName>
 *                           docname=<DocumentName>
 *                           path=<Path>
 *
 * Copyright:    Copyright (c) 2003, 2010
 * Company:      Ixiasoft Technologies Inc.
 *
 * @version      2.0
 * Modified:     2010-06-28
 */

import com.ixia.textmlserver.*;
import java.io.*;
import java.util.*;

public class GetDocument
{
    final static String TOKEN_USER     = "USER";
    final static String TOKEN_PASSWORD = "PASSWORD";
    final static String TOKEN_SERVER   = "SERVER";
    final static String TOKEN_DOCBASE  = "DOCBASE";
    final static String TOKEN_PATH     = "PATH";
    final static String TOKEN_DOCNAME  = "DOCNAME";

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

    // Which parameters must be specified in command-line
    final static boolean[] mandatory   =
        { true      , true          , true        , true         ,
          true      , true };


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

        for (int i = 0; i < args.length; ++i)
        {
            StringTokenizer tokens = new StringTokenizer(args[i], "=", false);
            String token = null, value = null;

            if (tokens.hasMoreElements())
                token = tokens.nextToken();
            if (tokens.hasMoreElements())
                value = tokens.nextToken();

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

            boolean found = false;
            for (int j = 0; j < validTokens.length && !found; ++j)
            {
                if (validTokens[j].equalsIgnoreCase(token) &&
                    !retval.containsKey(validTokens[j]))
                {
                    retval.put(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;
    }


    // If run-time parameters are missing or invalid, display Help
    private static void Usage()
    {
        System.out.println
            ("GetDocument user=<domain\\user> password=<password> " +
             "server=<ServerName> docbase=<DocBaseName> "           +
             "docname=<DocumentName> path=<path>");
        System.out.println
            ("\t<domain\\user> name of the user used for security purpose");
        System.out.println
            ("\t<password> password of the user");
        System.out.println
            ("\t<ServerName> Textmlserver name");
        System.out.println
            ("\t<DocBaseName> Document base name");
        System.out.println
            ("\t<DocumentName> Name of the document to retrieve");
        System.out.println
            ("\t<path> The path where the document will be saved");
    }


    // Save the <content> of the document to path\file <filename>
    private static void WriteFile
        (String fileName, IxiaDocument.Content content)
        throws java.io.IOException
    {
        FileOutputStream f = new FileOutputStream(fileName);

        try
        {
            content.SaveTo(f);
        }
        finally
        {
            f.close();
        }
    }


    // Save String <strContent> to file <filename>, a Unicode-16 file
    private static void WriteFile(String fileName, String strContent)
                                 throws java.io.IOException
    {
        OutputStreamWriter f =
            new OutputStreamWriter(new FileOutputStream(fileName),
                                  "UTF-16LE");  // 16-bit little-endian

        try
        {
            f.write("\ufeff"); //  BOM for 16-bit little-endian Unicode file
            f.write(strContent);
        }
        finally
        {
            f.close();
        }
    }


    // Main routine
    public static void main(String[] args)
    {

        // Parse the command line
        HashMap<String, String> map = Extract(args);

        // Validate the parameters
        if (map.isEmpty())
        {
            Usage();
            return;
        }

        String user = (String) map.get(TOKEN_USER);

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

        String documentName = (String) map.get(TOKEN_DOCNAME);
        String path         = (String) map.get(TOKEN_PATH);

        // Prepare parameters for ClientServicesFactory
        HashMap<String, String> parms = new HashMap<String, String>(1);

        try
        {
            // Get the ClientServices object
            ClientServices cs =
                com.ixia.textmlserver.ClientServicesFactory.getInstance
                    ("CORBA", parms);

            // 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.get(TOKEN_PASSWORD));

            try
            {
                // Get the ServerServices for the server specified by the user
                IxiaServerServices ss =
                    cs.ConnectServer((String) map.get(TOKEN_SERVER));

                try
                {
                    // Get the DocbaseServices for the specified docbase
                    // on that server
                    IxiaDocBaseServices docbase =
                        ss.ConnectDocBase((String) map.get(TOKEN_DOCBASE));
                    try
                    {
                        // Get the DocumentServices for the specified docbase
                        IxiaDocumentServices ds = docbase.DocumentServices();

                        try
                        {
                            // Prepare an array big enough to hold the names
                            // of the documents to be retrieved.
                            // We are only retrieving one document.
                            String [] documents = new String[1];
                            documents[0] = documentName;

                            // Get the specified documents.
                            // We want:
                            // -- the actual content of the document
                            //    (normally XML).
                            // -- the document's properties
                            // The document is a "user document".

                            IxiaDocumentServices.Result [] result =
                                ds.GetDocuments(documents,
                                    Constants.TEXTML_DOCUMENT_CONTENT |
                                    Constants.TEXTML_DOCUMENT_PROPERTIES,
                                    Constants.TEXTML_DOCUMENT);

                            // A Result object has two fields:
                            // -- a Document object.
                            // -- an Error object.
                            if (result == null) // Should not ever happen
                            {
                                System.out.println
                                    ("An unexpected error occurred");
                                return;
                            }
                            // An error occurred for this document
                            else if (result[0].error != null)
                            {
                                // Handle expected errors
                                if (result[0].error.GetErrorCode() ==
                                    TextmlserverError.TEXTML_E_TRANSACTION_LOG)
                                {
                                    // Get a list of events for this document
                                    Iterator events =
                                        result[0].error.GetEvents();

                                    // Display all the events
                                    while (events.hasNext())
                                    {
                                      TextmlserverError.Event event =
                                        (TextmlserverError.Event) events.next();
                                      System.err.println (event.toString());
                                    }
                                }
                            }

                            if (result[0].error != null)
                            {
                             System.err.println
                               ("The following error occurred while getting " +
                                documentName);
                             System.err.println(result[0].error.getMessage());
                             return;
                            }

                            WriteFile(path + File.separator +
                                      result[0].document.GetName(),
                                      result[0].document.GetContent());

                            System.out.println
                                (documentName + " successfully saved.") ;

                            WriteFile
                                (path + File.separator +
                                "P_" + result[0].document.GetName() + ".xml",
                                result[0].document.GetProperties());

                            System.out.println
                                (documentName +
                                 "'s properties successfully saved.");
                        }
                        finally
                        {
                            ds.Release();  // Free this object's memory
                        }
                    }
                    finally
                    {
                        docbase.Release();
                    }
                }
                finally
                {
                    ss.Release();
                }
            }
            finally
            {
                // don't forget to logout
                cs.Logout();
            }
        }
        catch (Exception e)
        {
            System.err.println("Exception occurred: ");
            e.printStackTrace(System.err);
        }

    }
}