Thursday, July 3, 2014

example JAVA, creating a new text file


package filetest;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;


public class FileTest
{

    public static void main(String[] args)
    {
        try
        {
            File myfile = new File("myfile.txt");
            if (myfile.exists())
            {
                System.out.println("myfile.txt exists");
                Boolean success_delete = myfile.delete();
                if (success_delete)
                    System.out.println("myfile.txt successfully deleted");
                else
                    System.out.println("myfile.txt failed on delete!");
            }
           
            Boolean success_create = myfile.createNewFile();
            if (success_create)
                System.out.println("myfile.txt successfully created");
            else
                System.out.println("myfile.txt failed on create!");
           
            FileWriter fw = new FileWriter(myfile);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("hello");
            bw.newLine();
            bw.write("goodbye");
            bw.newLine();
            bw.write("cheeseburger");
            bw.newLine();
            bw.write("french fries");
            bw.flush();
            System.out.println("myfile.txt wrote lines");
           
            bw.close();
            fw.close();
            System.out.println("myfile.txt closing file");
     
        }
        catch (Exception ex)
        {
            System.out.println("EXCEPTION WAS THROWN AND CAUGHT!");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
   
}//FileTest

DEMO #1 java, JDBC and oracle db, with file output


package report_finals;

import java.util.ArrayDeque;
import java.io.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import oracle.jdbc.*;


public class REPORT_FINALS
{
    
    public static int ReadInputFile(ArrayDeque<String> ssn_queue)
    {
        int status        = 0;
        FileReader fr     = null;
        BufferedReader br = null;
        try
        {
            try
            {
                fr = new FileReader("C:\\Users\\leem\\Desktop\\tab_delimit_test.txt");
            }
            catch (FileNotFoundException e)
            {
                throw new Exception("ReadInputFile ERROR: Can not find input text csv file!");
            }
            System.out.println("ReadInputFile: Found input text csv file");

            br = new BufferedReader(fr);
            String myline;
            int datalinecount = 0;
        
            myline = br.readLine(); //first line should be header line of .csv file
            myline = br.readLine(); //second line should be data line of .csv file
            while (myline != null)
            {
                datalinecount++;
                
                int name_idx   = myline.indexOf('\t');
                int ssn_idx    = myline.indexOf('\t', name_idx+1);
                int plan_idx   = myline.indexOf('\t', ssn_idx+1);
                
                String name_str   = myline.substring(0, name_idx);
                String ssn_str    = myline.substring(name_idx+1, ssn_idx);
                String plan_str   = myline.substring(ssn_idx+1, plan_idx);
                String retire_str = myline.substring(plan_idx+1);
                
                //validate ssn string
                if (ssn_str.length() != 11)
                {
                    System.out.println(ssn_str);
                    System.out.println(myline);
                    throw new Exception("ReadInputFile ERROR: Found a ssn string not length 11!");
                }
                int dash1_idx = ssn_str.indexOf('-');
                int dash2_idx = ssn_str.indexOf('-', dash1_idx+1);
                if (dash1_idx != 3 || dash2_idx != 6)
                {
                    System.out.println(ssn_str);
                    System.out.println(myline);
                    throw new Exception("ReadInputFile ERROR: Dashes in ssn string not correct!");
                }
                String ssn_final = ssn_str.substring(0, 3) + ssn_str.substring(4, 6) + ssn_str.substring(7);
                //The call to Integer.decode below does not like 0 in the beginning of the string
                //So we will take out any leading 0 characters.
                String checkzerostr = ssn_final;
                while (checkzerostr.charAt(0) == '0')
                    checkzerostr = checkzerostr.substring(1);
                
                Integer mytestint = null;
                try
                {
                    mytestint = Integer.decode(checkzerostr);
                }
                catch (NumberFormatException e)
                {
                    System.out.println(ssn_final);
                    System.out.println(myline);
                    throw new Exception("ReadInputFile ERROR: one of the ssn numbers has a bad format!");
                }
                
                try
                {
                    ssn_queue.addLast(ssn_final);
                }
                catch (Exception ex)
                {
                    System.out.println(ssn_final);
                    System.out.println(myline);
                    throw new Exception("ReadInputFile ERROR: caught exception trying to add to ssn_queue!");
                }
                
                myline = br.readLine();
            }//while myline
            
            if (datalinecount == ssn_queue.size())
                System.out.println(String.format("ReadInputFile: ssn_queue size = datalinecount = %d", datalinecount));
            else
            {
                throw new Exception("ReadInputFile ERROR: ssn_queue size != datalinecount");
            }
            System.out.println("ReadInputFile: Read all of input text csv file");
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("ReadInputFile ERROR: CAUGHT EXCEPTION RETURNING STATUS TO MAIN!");
            System.out.println(ex.getMessage());
            ex.printStackTrace();  
        }
        finally
        {
            try
            {
                if (br != null)
                    br.close();
                if (fr != null)
                    fr.close();
            }
            catch (Exception ex)
            {
                System.out.println("ReadInputFile ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//ReadInputFile
    
    public static int CreateTemporaryTables(ArrayDeque<String> ssn_queue)
    {
        //***********************************************
        //BEGIN DOING DATABASE STUFF
        //***********************************************
        int status = 0;
        Connection connect = null;
        Statement stmt     = null;
        try
        {
            try 
            {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            }
            catch (ClassNotFoundException e)
            {
                throw new Exception("CreateTemporaryTables ERROR: Oracle classes not found!");
            }
            System.out.println("CreateTemporaryTables: Found oracle.jdbc.driver.OracleDriver");
 
            try
            {
                connect = DriverManager.getConnection("jdbc:oracle:thin:@10.50.1.30:1521:v3uat", "miyamotok", "miyamotok");
            }
            catch (SQLException e)
            {
                throw new Exception("CreateTemporaryTables ERROR: Problem connecting to db");
            }
            System.out.println("CreateTemporaryTables: Successful connection to db");
 
            try
            {
                stmt = connect.createStatement();
                
                try
                {
                    String drop_old_table_str = "drop table SSN_TEMP_TABLE";
                    stmt.execute(drop_old_table_str);
                }
                catch (Exception ex)
                {
                    System.out.println("CreateTemporaryTables: IGNORING exception dropping table SSN_TEMP_TABLE, probably table does not exist");
                }
                
                String ssn_table_str = "create table SSN_TEMP_TABLE(SSN varchar2(20))";
                stmt.execute(ssn_table_str);
                System.out.println("CreateTemporaryTables: SSN Table Created Successfully");
                
                for (int ii=0; ii < ssn_queue.size(); ii++)
                {
                    String insertRecStr   = String.format("insert into SSN_TEMP_TABLE values('%s')", ssn_queue.removeFirst());
                    stmt.execute(insertRecStr);
                }
                System.out.println("CreateTemporaryTables: Added all SSN numbers");
                
                try
                {
                    String drop_old_table_str = "drop table WH_OUTPUT_TEMP_TABLE";
                    stmt.execute(drop_old_table_str);
                }
                catch (Exception ex)
                {
                    System.out.println("CreateTemporaryTables: IGNORING exception dropping table WH_OUTPUT_TEMP_TABLE, probably table does not exist");
                }
                
                String wh_table_str = "create table WH_OUTPUT_TEMP_TABLE as ";
                wh_table_str       += "select  me.sort_name||' wh' Name ";
                wh_table_str       += "       ,me.ssn SSN ";
                wh_table_str       += "       ,e.employer_name employer_name ";
                wh_table_str       += "       ,be.billing_entity_name Billing_location_name ";
                wh_table_str       += "       ,wr.outer_start_date Report_period_start ";
                wh_table_str       += "       ,wh1.start_date Earning_period_start_date ";
                wh_table_str       += "       ,wh1.stop_date Earning_period_end_date ";
                wh_table_str       += "       ,wh1.wh_release_status WH_release_status ";
                wh_table_str       += "       ,wh1.pay_code ";
                wh_table_str       += "       ,wh1.code_05 Payment_date ";
                wh_table_str       += "       ,(NVL(WH1.WORK_01, 0)) Base_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_02, 0)) Gross_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_03, 0))Reg_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_04, 0)) Vac_pay ";
                wh_table_str       += "       ,wh1.code_06 Retro_pay_type ";
                wh_table_str       += "       ,(NVL(WH1.WORK_05, 0)) Retro_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_06, 0)) WC_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_07, 0)) SAB_LV_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_08, 0)) Other_pay ";
                wh_table_str       += "       ,(NVL(WH1.WORK_09, 0)) Normal_AS ";
                wh_table_str       += "       ,(NVL(wh1.work_10, 0)) ADDL_AS ";
                wh_table_str       += "       ,wh1.work_14 Diff_Pay_Recurring ";
                wh_table_str       += "       ,wh1.work_15 Diff_Pay_Non_Recurring ";
                wh_table_str       += "       ,wh1.work_16 Num_hours_worked ";
                wh_table_str       += "       ,wh1.work_11 Calculated_days ";
                wh_table_str       += "       ,wh1.work_12 FTE ";
                wh_table_str       += "       ,wh1.work_18 Pay_rate ";
                wh_table_str       += "       ,(NVL(wh1.work_13,0)) Elig_comp ";
                wh_table_str       += "       ,wh1.code_01 Group_code ";
                wh_table_str       += "       ,wh1.code_02 Class_code ";
                wh_table_str       += "from dbo.work_history_1  wh1, ";
                wh_table_str       += "     dbo.work_report     wr, ";
                wh_table_str       += "     dbo.v_member_q      me, ";
                wh_table_str       += "     dbo.employer        e, ";
                wh_table_str       += "     dbo.billing_entity  be, ";
                wh_table_str       += "     SSN_TEMP_TABLE      f ";
                wh_table_str       += "where     wh1.billing_id               = be.billing_id(+) ";
                wh_table_str       += "      and wh1.employer_id              = e.employer_id(+) ";
                wh_table_str       += "      and wh1.member_id                = me.member_id(+) ";
                wh_table_str       += "      and wh1.report_id                = wr.report_id(+) ";
                wh_table_str       += "      and me.ssn                       = f.ssn ";
                wh_table_str       += "      and wh1.stop_date is not null ";
                wh_table_str       += "Order by me.ssn";
                stmt.execute(wh_table_str);
                System.out.println("CreateTemporaryTables: WH Table Created Successfully");
                
                try
                {
                    String drop_old_table_str = "drop table PH_OUTPUT_TEMP_TABLE";
                    stmt.execute(drop_old_table_str);
                }
                catch (Exception ex)
                {
                    System.out.println("CreateTemporaryTables: IGNORING exception dropping table PH_OUTPUT_TEMP_TABLE, probably table does not exist");
                }
                
                String ph_table_str = "create table PH_OUTPUT_TEMP_TABLE as ";
                ph_table_str       += "select  me.sort_name||' Ph' Name ";
                ph_table_str       += "       ,me.ssn SSN ";
                ph_table_str       += "       , ph.column_value_01 Start_date ";
                ph_table_str       += "       , ph.column_value_02 Stop_date ";
                ph_table_str       += "       , ph.column_value_04 cred ";
                ph_table_str       += "       , ph.column_value_06 Hcomp ";
                ph_table_str       += "       , ph.column_value_08 Acomp ";
                ph_table_str       += "       , ph.column_value_07 Ccomp ";
                ph_table_str       += "       , ph.column_value_03 Trans_type ";
                ph_table_str       += "       , ph.column_value_11 elig_comp ";
                ph_table_str       += "       , ph.column_value_15 Job_class ";
                ph_table_str       += "       , ph.column_value_13 Vac_pay ";
                ph_table_str       += "       , ph.column_value_16 Forfeited ";
                ph_table_str       += "from dbo.pension_history ph, ";
                ph_table_str       += "     dbo.pension_application pa, ";
                ph_table_str       += "     dbo.v_member_q          me, ";
                ph_table_str       += "     SSN_TEMP_TABLE          f ";
                ph_table_str       += "where ph.member_id         = me.member_id(+) ";
                ph_table_str       += "     and ph.application_id = pa.application_id ";
                ph_table_str       += "     and pa.application_id is not null ";
                ph_table_str       += "     and me.ssn            = f.ssn  ";
                ph_table_str       += "Order by me.ssn ";
                stmt.execute(ph_table_str);
                System.out.println("CreateTemporaryTables: PH Table Created Successfully");
            }
            catch (SQLException e)
            {
                throw new Exception("CreateTemporaryTables ERROR: Problem executing db commands!");
            }
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("CreateTemporaryTables ERROR: CAUGHT EXCEPTION RETURNING STATUS TO MAIN!");
            System.out.println(ex.getMessage());
            ex.printStackTrace();  
        }
        finally
        {
            try
            {
                if (connect != null)
                    connect.close();
                if (stmt != null)
                    stmt.close();
            }
            catch (Exception ex)
            {
                System.out.println("CreateTemporaryTables ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//CreateTemporaryTables
    
    public static int CreateOutputFiles()
    {
        //**************************************************************
        //Query our 2 result tables
        //and make output files.
        //**************************************************************
        Connection     connect = null;
        Statement      stmt = null;
        ResultSet      rs = null;
        File           myfile = null;
        FileWriter     fw = null;
        BufferedWriter bw = null;
        int status = 0;
        try
        {
            connect = DriverManager.getConnection("jdbc:oracle:thin:@10.50.1.30:1521:v3uat", "miyamotok", "miyamotok");
            String query_wh = "SELECT * FROM WH_OUTPUT_TEMP_TABLE";
            stmt = connect.createStatement();
            rs = stmt.executeQuery(query_wh);

            myfile = new File("wh_output.txt");
            if (myfile.exists())
            {
                System.out.println("CreateOutputFiles: wh_output.txt exists");
                Boolean success_delete = myfile.delete();
                if (success_delete)
                    System.out.println("CreateOutputFiles: wh_output.txt successfully deleted");
                else
                    System.out.println("CreateOutputFiles: wh_output.txt failed on delete!");
            }

            Boolean success_create = myfile.createNewFile();
            if (success_create)
                System.out.println("CreateOutputFiles: wh_output.txt successfully created");
            else
                System.out.println("CreateOutputFiles: wh_output.txt failed on create!");

            fw = new FileWriter(myfile);
            bw = new BufferedWriter(fw);
            
            bw.write("NAME\t");
            bw.write("SSN\t");
            bw.write("EMPLOYER_NAME\t");    
            bw.write("BILLING_LOCATION_NAME\t");    
            bw.write("REPORT_PERIOD_START\t");    
            bw.write("EARNING_PERIOD_START_DATE\t");    
            bw.write("EARNING_PERIOD_END_DATE\t");    
            bw.write("WH_RELEASE_STATUS\t");    
            bw.write("PAY_CODE\t");    
            bw.write("PAYMENT_DATE\t");    
            bw.write("BASE_PAY\t");    
            bw.write("GROSS_PAY\t");    
            bw.write("REG_PAY\t");    
            bw.write("VAC_PAY\t");    
            bw.write("RETRO_PAY_TYPE\t");    
            bw.write("RETRO_PAY\t");    
            bw.write("WC_PAY\t");    
            bw.write("SAB_LV_PAY\t");    
            bw.write("OTHER_PAY\t");    
            bw.write("NORMAL_AS\t");    
            bw.write("ADDL_AS\t");    
            bw.write("DIFF_PAY_RECURRING\t");    
            bw.write("DIFF_PAY_NON_RECURRING\t");    
            bw.write("NUM_HOURS_WORKED\t");    
            bw.write("CALCULATED_DAYS\t");    
            bw.write("FTE\t");    
            bw.write("PAY_RATE\t");    
            bw.write("ELIG_COMP\t");    
            bw.write("GROUP_CODE\t");    
            bw.write("CLASS_CODE\t");
            bw.newLine();
            
            int linecount = 0;
            while (rs.next())
            {
                linecount++;
                StringBuilder sb = new StringBuilder();
                sb.append(rs.getString("NAME"));
                sb.append('\t');
                sb.append(rs.getString("SSN"));
                sb.append('\t');
                sb.append(rs.getString("EMPLOYER_NAME"));
                sb.append('\t');
                sb.append(rs.getString("BILLING_LOCATION_NAME"));
                sb.append('\t');
                sb.append(rs.getString("REPORT_PERIOD_START"));
                sb.append('\t');
                sb.append(rs.getString("EARNING_PERIOD_START_DATE"));
                sb.append('\t');
                sb.append(rs.getString("EARNING_PERIOD_END_DATE"));
                sb.append('\t');
                sb.append(rs.getString("WH_RELEASE_STATUS"));
                sb.append('\t');
                sb.append(rs.getString("PAY_CODE"));
                sb.append('\t');
                sb.append(rs.getString("PAYMENT_DATE"));
                sb.append('\t');
                sb.append(rs.getString("BASE_PAY"));
                sb.append('\t');
                sb.append(rs.getString("GROSS_PAY"));
                sb.append('\t');
                sb.append(rs.getString("REG_PAY"));
                sb.append('\t');
                sb.append(rs.getString("VAC_PAY"));
                sb.append('\t');
                sb.append(rs.getString("RETRO_PAY_TYPE"));
                sb.append('\t');
                sb.append(rs.getString("RETRO_PAY"));
                sb.append('\t');
                sb.append(rs.getString("WC_PAY"));
                sb.append('\t');
                sb.append(rs.getString("SAB_LV_PAY"));
                sb.append('\t');
                sb.append(rs.getString("OTHER_PAY"));
                sb.append('\t');
                sb.append(rs.getString("NORMAL_AS"));
                sb.append('\t');
                sb.append(rs.getString("ADDL_AS"));
                sb.append('\t');
                sb.append(rs.getString("DIFF_PAY_RECURRING"));
                sb.append('\t');
                sb.append(rs.getString("DIFF_PAY_NON_RECURRING"));
                sb.append('\t');
                sb.append(rs.getString("NUM_HOURS_WORKED"));
                sb.append('\t');
                sb.append(rs.getString("CALCULATED_DAYS"));
                sb.append('\t');
                sb.append(rs.getString("FTE"));
                sb.append('\t');
                sb.append(rs.getString("PAY_RATE"));
                sb.append('\t');
                sb.append(rs.getString("ELIG_COMP"));
                sb.append('\t');
                sb.append(rs.getString("GROUP_CODE"));
                sb.append('\t');
                sb.append(rs.getString("CLASS_CODE"));
                bw.write(sb.toString());
                bw.newLine();
            }

            bw.flush();
            System.out.println(String.format("CreateOutputFiles: wh_output.txt wrote %d lines", linecount));
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("CreateOutputFiles ERROR: CAUGHT EXCEPTION RETURNING STATUS TO MAIN!");
            System.out.println(ex.getMessage());
            ex.printStackTrace();  
        }
        finally
        {
            try
            {
                if (connect != null)
                    connect.close();
                if (stmt != null)
                    stmt.close();
                if (rs != null)
                    rs.close();
                if (fw != null)
                    fw.close();
                if (bw != null)
                    bw.close();
            }
            catch (Exception ex)
            {
                System.out.println("CreateOutputFiles ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//CreateOutputFiles
    
    public static void main(String[] args) 
    {
        //*******************************************************
        //Read tab delimited text file containing SSN numbers
        //Order of columns is:
        //NAME  SSN  PLAN  RETIREMENT_DATE
        //Put the SSN numbers into ssn_queue.
        //*******************************************************
        ArrayDeque<String> ssn_queue = new ArrayDeque<String>();
        
        int status = ReadInputFile(ssn_queue);
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from ReadInputFile EXITING PROGRAM");
            return;
        }
        
        status = CreateTemporaryTables(ssn_queue);
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from CreateTemporaryTables EXITING PROGRAM");
            return;
        }
        
        status = CreateOutputFiles();
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from CreateOutputFiles EXITING PROGRAM");
            return;
        }
        
        System.out.println("DONE");
    }//main  
}//class REPORT_FINALS


Tuesday, July 1, 2014

example JAVA scanning directorys for files



package mappeddrivetest;

import java.nio.file.*;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Date;
import java.util.ArrayDeque;
import java.io.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;


public class MappedDriveTest
{

    public static void ScanDirectory(ArrayList sentpaths, String searchdir)
    {
        try
        {
            File ff = new File(searchdir);
            //if (ff == null)
            //    System.out.println("ff is null");
            //else
            //    System.out.println("ff is not null");
            File[] myfiles = ff.listFiles();
            //if (myfiles == null)
            //    System.out.println("myfiles is null");
            //else
            //    System.out.println("myfiles is not null");
           
            for (int ii=0; ii < myfiles.length; ii++)
            {
                if (myfiles[ii].isFile())
                {
                    String upperstr = myfiles[ii].toString().toUpperCase();
                    if (upperstr.endsWith(".SENT"))
                    {
                        sentpaths.add(upperstr);
                    }
                }
                else if (myfiles[ii].isDirectory())
                {
                    ScanDirectory(sentpaths, myfiles[ii].toString());
                }
            }
        }
        catch (Exception ex)
        {
             System.out.println("ERROR: Exception caught inside ScanDirectory!");
             ex.printStackTrace();
        }
    }//ScanDirectory
   
    public static void main(String[] args)
    {
        String searchdir = "C:\\Users\\leem\\TEST_DATA\\";
        //String searchdir = "P:\\ERS\\CLASS_CODE_Data";
        //String searchdir   = "\\\\s067y2wpb1\\Developers";
       
        ArrayList sentpaths = new ArrayList();
        ScanDirectory(sentpaths, searchdir);
        for (int ii=0; ii < sentpaths.size(); ii++)
        {
            String tempstr = String.format("%d/%d: %s", ii, sentpaths.size(), sentpaths.get(ii));
            System.out.println(tempstr);
        }
        System.out.println("DONE");
    }//Main
   
}//MappedDriveTest