//
//   Source File Name: ShowPic.java  1.3 
//  
//   Licensed Materials -- Property of IBM 
//  
//   (c) Copyright International Business Machines Corporation, 1999. 
//       All Rights Reserved. 
//  
//   US Government Users Restricted Rights - 
//   Use, duplication or disclosure restricted by 
//   GSA ADP Schedule Contract with IBM Corp. 
//  
//     PURPOSE : 
//         - Lists all employees with pictures, and prompts the user to 
//           select a picture (BLOB) from the emp_photo table 
//         - Writes a file of the indicated type (xwd, bmp, or gif)  
//           to the current directory 

//  For more information about this sample, refer to the README file. 

//  For more information on Programming in Java, refer to the  
//  "Programming in Java" section of the Application Development Guide. 

//  For more information on building and running Java programs for DB2, 
//  refer to the "Building Java Applets and Applications" section of the  
//  Application Building Guide. 

//  For more information on the SQL language, refer to the SQL Reference. 

import java.io.*;
import java.lang.*;
import java.sql.*;

class ShowPic {

   static {
      try {
         //  register the driver with DriverManager 
         //  The newInstance() call is needed for the sample to work with 
         //  JDK 1.1.1 on OS/2, where the Class.forName() method does not 
         //  run the static initializer. For other JDKs, the newInstance 
         //  call can be omitted. 
         Class.forName("COM.ibm.db2.jdbc.app.DB2Driver").newInstance();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main (String[] argv) {
      Connection con = null;
      int MAX_FILE_SIZE = 102400;

      try {
         //  connect with id/password 
         if (argv.length == 3)
         {  //  connect using command line arguments 
            con = Tools.DBConnect(argv[0], argv[1], argv[2]); 
         }
         else
         {  //  prompt user for database name, user ID, password 
            con = Tools.DBConnect(); 
         }
         con.setAutoCommit(false);

         String photoFormat = selectPicFormat();
         String fileFormat = new String("");
         if (photoFormat.length() >= 4) { fileFormat = "bmp"; }
         else { fileFormat = photoFormat; }

         displayEmployees (con, photoFormat);
         System.out.println ("Select an Employee Number from the list above");
         String empNo = Tools.readString();
         byte[] picData = new byte[MAX_FILE_SIZE];

         if (getPicture (con, empNo, photoFormat, picData)) {
            String fileName = "P" + empNo + "." + fileFormat;
            createFile (picData, fileName, fileFormat);

         }
         else { System.out.println ("A photograph for that user does not exist!"); }

         // disconnect from connection made to server and commit transactions 
         System.out.println ("\n>Disconnecting...\n");
         con.commit();
         con.close();
      } catch (Exception e) { e.printStackTrace(); }
   }

  //  
  //  selectPicFormat 
  //     - ensures that user choices appropriate picture format 
  //     - returns selected format 
  //  

   public static String selectPicFormat() {
      String picFormat = new String("");
      try {
         //  ask user to enter file format until format is correct 
         boolean correctFormat = false;
         while (!correctFormat) {
            System.out.println ("Which Picture Format [xwd (XWindows), bitmap, gif]?");
            picFormat = Tools.readString().toLowerCase();
            if (picFormat.equals("xwd") || picFormat.equals("bitmap") || picFormat.equals("gif")) {
               correctFormat = true;
            }
            if (!correctFormat) { System.out.println ("Invalid Format!"); }
         }
      } catch (Exception e) { e.printStackTrace(); }
      return picFormat;  //  return format selected by user 
   }


  //  
  //  displayEmployees 
  //     - queries the sample server to display employee names which match format 
  //  

   public static void displayEmployees (Connection con, String picFormat) {
      try {
         //  select all employees where their number matches the numbers 
         //  from emp_photo with selected photo format 
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery ("SELECT employee.empno, firstnme || lastname as name " +
            "from employee, emp_photo WHERE employee.empno = emp_photo.empno and " +
	    "photo_format = '" + picFormat + "'");

         System.out.println ("Empno\t Name");
         System.out.println ("-------- ---------------------");
         String name = new String("");
         String id = new String("");

         //  print list of all employees with photos 
         while (rs.next()) {
            id = rs.getString (1);
            name =  rs.getString (2);
            System.out.println(Tools.padLength(id, 8) + " " + name);
         }
         rs.close();
         stmt.close();
      } catch (Exception e) { e.printStackTrace(); }
   }


  //  
  //  getPicture 
  //     - retrieved BLOB from table and stores it in and array of bytes 
  //     - if successful then return true 
  //  

   public static boolean getPicture (Connection con, String empNo, String photoFormat, byte[] picData) {
      boolean picExists = false;
      try {
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery ("SELECT picture FROM emp_photo WHERE " +
	    "empno  = '" + empNo + "' AND photo_format = '" + photoFormat +"'");
         //  since there was data retrieved from the query the picture must exist 
         if (rs.next()) {
            picExists = true;
            //  input data from the source (database) and store in the byte array Data 
            InputStream is = rs.getBinaryStream (1);
            is.read (picData);
         }
         else { picExists = false; }
         rs.close();
         stmt.close();
      } catch (Exception e) { e.printStackTrace(); }
      return picExists;
   }

  //  
  //  createFile 
  //     - tells user what file will be created and copies data from data to file 
  //  

   public static void createFile (byte[] data, String fileName, String fileType) {
      try {
         System.out.println ("Will create file: " + fileName);
 
         //  store data retrieved from array (data) in a file 
         FileOutputStream fos = new FileOutputStream (fileName);
         fos.write (data);
         fos.close();
         System.out.print (fileName + " has been successfully created");
      } catch (Exception e) { e.printStackTrace(); }
   }
}