//Warning: This code has been marked up for HTML
/***************************************************************************
$name: ExecuteQuery.java
$version: 1.0
$date_modified: 020300
$description: Executes an SQL query and writes the result to a text file
$owner: JDBC Driver Product Manager
Copyright (c) 1998 Novell, Inc. All Rights Reserved.

THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND TREATIES.
USE AND REDISTRIBUTION OF THIS WORK IS SUBJECT TO THE LICENSE AGREEMENT
ACCOMPANYING THE SOFTWARE DEVELOPMENT KIT (SDK) THAT CONTAINS THIS WORK.
PURSUANT TO THE SDK LICENSE AGREEMENT, NOVELL HEREBY GRANTS TO DEVELOPER A
ROYALTY-FREE, NON-EXCLUSIVE LICENSE TO INCLUDE NOVELL'S SAMPLE CODE IN ITS
PRODUCT. NOVELL GRANTS DEVELOPER WORLDWIDE DISTRIBUTION RIGHTS TO MARKET,
DISTRIBUTE, OR SELL NOVELL'S SAMPLE CODE AS A COMPONENT OF DEVELOPER'S
PRODUCTS. NOVELL SHALL HAVE NO OBLIGATIONS TO DEVELOPER OR DEVELOPER'S
CUSTOMERS WITH RESPECT TO THIS CODE.
****************************************************************************/
import java.util.*;
import java.sql.*;
import java.io.*;

    /**
     * The main method of this class will execute an SQL query contained in
     * a text file and output the results to a text file named
     * ExecuteQuery.txt
     *
     * The main method takes five command line arguments as listed below.
     *
     *   <server> - the IP address or domain name of the LDAP server.
     *      The default LDAP port is assumed.
     *   <user> - the complete distinguished name of the user to bind as.
     *   <password> - the password for the user.
     *   <baseDN> - the distinguished name for the container from which the
     *      results will be generated.
     *   <query file> - the name of the text file containing the SQL query.
     */

class ExecuteQuery
{
   public static void main(
      String args[])
   {
      String      query;
      String      server;
      String      user;
      String      password;
      String      baseDN;
      String      queryFile;
      String      url;
      PrintWriter outFile;

     //get arguments

      if (args.length != 5)
      {
         System.out.println(
          "Usage: java ExecuteQuery <server> <user> <password> <baseDN> <query file>");
         System.out.println(
          "Example: java ExecuteQuery 139.48.122.134 " +
           "cn=tjones,ou=sales,o=acme mypassword ou=sales,o=acme query1.sql");
      }
      else
      {
         server = args[0];
         user = args[1];
         password = args[2];
         baseDN = args[3];
         queryFile = args[4];

         try
         {
           //load the driver

            System.out.println("loading driver class");
            Class.forName("com.novell.sql.LDAPDriver");
            System.out.println("loading driver class");

           //get a driver instance

            Driver driver = DriverManager.getDriver("jdbc:ldap");

            url = "jdbc:ldap://" + server +
                  ";user=" + user +
                  ";password=" + password +
                  ";baseDN=" + baseDN +
                  ";useCleartext=true";

            Connection conn = driver.connect(url, null);

            Statement statement = conn.createStatement();

            query = readQuery(queryFile);

            ResultSet result = statement.executeQuery(query);

            printResults(result);

            conn.close();
         }
         catch (SQLException e)
         {
            System.out.println(e.toString());
         }
         catch (ClassNotFoundException e)
         {
            System.out.println(
            "Could not find the Driver Class: com.novell.sql.LDAPDriver");
         }
         catch(java.lang.NullPointerException e)
         {
            System.out.println(e.toString());
            e.printStackTrace();
         }
      }

   }//end main method


/***************************************************************************/
/* Read the query from the specified file                                  */
/***************************************************************************/
   static String readQuery(
      String   fileName)
   {
      BufferedReader in;
      String         line;
      String         query = "";

      try
      {
         in = new BufferedReader(new FileReader(fileName));
         while ( (line = in.readLine()) != null)
         {
            if (query.length() != 0)
               query += " "; //ensure a space between words

            query += line;
         }

      }
      catch(FileNotFoundException e)
      {
         if (fileName.toLowerCase().startsWith("select"))
            query = fileName; //assume a query was defined on the command line

      }
      catch (IOException e)
      {
         System.out.println(e.toString());
      }

      return query;
   }

/***************************************************************************/
/* Print the results                                                       */
/***************************************************************************/
   static void printResults(
      ResultSet   result)
   {
      ResultSetMetaData metaData;
      int   columnCount;
      int   i;
      PrintWriter out;

      try
      {
         out
          = new PrintWriter(new BufferedWriter(new FileWriter("ExecuteQuery.txt")));

         metaData = result.getMetaData();
         columnCount = metaData.getColumnCount();
         System.out.println(columnCount + " columns in this result");
        // print column labels

         for (i=1; i<=columnCount; i++)
         {
            out.print('"');
            out.print(metaData.getColumnName(i));
            out.print('"');
            if (i != columnCount)
               out.print('\t');
            else
               out.println();
         }
         out.println("----------------------------------");
         while (result.next())
         {
             int j = 1;
            System.out.println("result #" + j++);
            for (i=1; i<=columnCount; i++)
            {
               System.out.println("\t#"+ i);
               if (i == 334){
                   System.out.println("this is where the error ocurrs");
               }
               out.print('"');
               out.print(result.getString(i));
               out.print('"');
               if (i < columnCount)
                  out.print('\t');
               else
                  out.println();
            }
         }

         out.flush();
         out.close();
      }
      catch(Exception e)
      {
         System.out.println(e);
         e.printStackTrace();
      }

   }//end method printResultSet


}//end class ExecuteQuery