Sunday, August 17, 2014

VB and simple MD5 hashing


http://roadha.us/2008/08/simple-md5-hashes-in-vb-net/

http://roadha.us/2008/08/simple-md5-hashes-in-vb-net/

Simple MD5 hashes in VB.NET

MD5 (Message Digest) hashes are a simple, efficient way to encode/encrypt information to be passed around. Rather than containing the data itself, an MD5 hash is merely a fingerprint of the information. The hash cannot be decrypted, but is instead compared to other hashed values for verification. This can be a handy tool when authenticating a user’s entered password as one simple example.
Here is a very efficient, simple function that can be used to generate an MD5 hash for a given string…
VB.NET 3.5 Code:
1
2
3
4
5
6
7
8
Public Function hashGen( _
ByVal sourceText As String) _
As String
    ' retrieve byte array based on source text, then
    ' compute hash and convert to string
    Return Convert.ToBase64String(New MD5CryptoServiceProvider(). _
        ComputeHash(New UnicodeEncoding().GetBytes(sourceText)))
End Function
In order to effectively use this hash value for verification, you will need a function that compares two hash values…
VB.NET 3.5 Code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
Public Function hashCompare( _
ByVal firstHash As String, _
ByVal compareText As String) _
As Boolean
    ' generate hash for compareText
    Dim compareHash = hashGen(compareText)
    ' if lengths are different, fail
    If firstHash.Length <> compareHash.Length Then
        Return False
    Else
        ' otherwise, compare value of each character
        Dim intCount As Integer = 0
        For intCount = 0 To firstHash.Length - 1
            ' fail if different
            If firstHash(intCount) <> compareHash(intCount) Then
                Return False
            End If
        Next
        Return True
    End If
End Function
These functions’ place in an authentication procedure would involve hashing a user’s entered password, for instance, and then comparing it to the hash generated from their LDAP password (or other password repository of sorts). Other examples of where MD5 may prove useful include checking sensitive user data, such as credit card numbers, home addresses, phone numbers… you name it.
Note: You may want to use the UTF8Encoding object (or some other encoder) instead of UnicodeEncoding, depending on the format of the data you will be comparing.

C# talking LDAP 4



http://roadha.us/2013/04/ldap-authentication-with-c-sharp/

http://roadha.us/2013/04/ldap-authentication-with-c-sharp/ 

LDAP authentication with C#

LDAP, or Lightweight Directory Access Protocol, is a convenient, central repository for a system’s personnel information. LDAP (and other Active Directory services) are widely-used by organizations big and small to consolidate user credentials and identification data. For instance: a reporting services application, a webmail client, and a database administration suite can all read from the same Directory, with no need for replicating user information. John Doe only has to remember one password for all systems. When he changes it, those changes cascade across the board.
Note: This is a translation of my original post, LDAP authentication with VB.NET, into the C# language.
Using C#, you can easily implement LDAP queries and authentication in your applications and websites. In this example, I will be creating a simple web application that verifies a user’s password—effectively “logging them in” to the system:
ASP.NET 2.0 Code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<%@ Page Language="C#"
    AutoEventWireup="true"
    CodeFile="Default.aspx.cs"
    Inherits="ldapLogin"
%>
<!DOCTYPE html PUBLIC
    "-//W3C//DTD XHTML 1.0 Transitional//EN"
<head runat="server">
    <title>LDAP Login</title>
</head>
<body>
    <form id="form1" runat="server">
        <div id="loginForm" runat="server" visible="false">
            Username:
            <br />
            <asp:TextBox ID="txtUsername" runat="server" />
            <p />
            Password:
            <br />
            <asp:TextBox TextMode="Password" ID="txtPassword" runat="server" />
            <p />
            <asp:Button ID="btnLogin" runat="server" Text="Login" />
        </div>
    </form>
</body>
</html>
The code-behind file for this page attempts to connect to the Active Directory server using the supplied user credentials, and responds with a respective message:
C# 3.5 Code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System.DirectoryServices;
partial class ldapLogin : System.Web.UI.Page
{
    // "login" button clicked
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        // build UID string
        String uid = "uid=" + txtUsername.Text + ",ou=people,dc=example,dc=com";
        // assign password
        String password = txtPassword.Text;
        // define LDAP connection
        DirectoryEntry root = new DirectoryEntry(
            "LDAP://directory.example.com", uid, password,
            AuthenticationTypes.None);
        try {
            // attempt to use LDAP connection
            object connected = root.Nativeobject;
            // no exception, login successful
            Response.Write("<span style=""color:green;"">Login successful.</span>");
        } catch (Exception ex) {
            // exception thrown, login failed
            Response.Write("<span style=""color:red;"">Login failed.</span>");
        }
        Response.Write("<p />");
    }
    // page load event
    protected void Page_Load(object Sender, EventArgs e)
    {
        if (IsPostBack) {
            // form submitted, hide login form
            loginForm.Visible = false;
        } else {
            // first page load, show login form
            loginForm.Visible = true;
        }
    }
}
The code makes a connection to the LDAP server using the supplied user credentials and domain information. The actual test for authentication happens on line 19, where the NativeObject member of the DirectoryEntry object is assigned to connected. If this assignment fails, the login was not authenticated, and the program will react accordingly.
Obviously, the uid and connection strings will have to be custom-tailored to your particular LDAP server. Also, the AuthenticationType property may need to be assigned a different value, depending on… can you guess? That’s right; the authentication method used by your LDAP server.

C# talking to LDAP 3

http://msdn.microsoft.com/en-us/library/9t2667d1%28v=vs.100%29
http://msdn.microsoft.com/en-us/library/9t2667d1%28v=vs.100%29

System.DirectoryServices  Namespace

 http://msdn.microsoft.com/en-us/library/cc136647.aspx

 http://msdn.microsoft.com/en-us/library/cc136647.aspx 

Windows 2003 --> Protocol Reference Archives --> About Lightweight Directory Access Protocols

C# talking to LDAP 2

http://its.uncg.edu/LDAP/Code_Examples/
http://its.uncg.edu/LDAP/Code_Examples/

The code below shows how to connect to the LDAP server and how to bind using the credentials entered by the user.
NOTE: The System.DirectoryServices library is commonly used for authentication and the process relies heavily on error handling. Please download the sample code found in the C# Links to better understand how to authenticate and authorize users within your application.
...
using System.DirectoryServices;
...
using ( DirectoryEntry entry = new DirectoryEntry() )
using ( DirectorySearcher search = new DirectorySearcher() )
{

    var accountDN = string.Format("cn={0},ou=accounts,o=uncg", username);
    entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;

    entry.Path = string.Format(@"LDAP://{0}:{1}/{2}", 
                               serverName, port, baseDn);
    entry.Username = accountDN;
    entry.Password = pwd;

    search.ServerTimeLimit = serverTimeout;
    search.ClientTimeout = clientTimeout;
    search.SearchRoot = entry;
    search.FindOne();

    entry.Close();
    entry.Dispose();
}
...
 
The code below shows how to lookup a user's department and preferred first name attributes.
...
using System.DirectoryServices;
...
using ( DirectoryEntry entry = new DirectoryEntry() )
using ( DirectorySearcher search = new DirectorySearcher() )
{

    var accountDN = string.Format("cn={0},ou=accounts,o=uncg", username);
    entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;

    if ( accountDN != null )
    {

        entry.Path = _requestPath;
        entry.Username = accountDN;
        entry.Password = pwd;

        search.ServerTimeLimit = serverTimeout;
        search.ClientTimeout = clientTimeout;
        search.SearchRoot = entry;
        search.Filter = string.Format(@"(cn={0})", username);

        search.PropertiesToLoad.Add("uncgpreferredgivenname");
        search.PropertiesToLoad.Add("departmentNumber");

        SearchResult attributes = search.FindOne();

        setProperties(attributes, accountDN);

        tmpReturn = true;
    }

    entry.Close();
    entry.Dispose();
}
...

C# talking to LDAP

http://msdn.microsoft.com/en-us/library/ms257181%28v=vs.80%29.aspx
http://msdn.microsoft.com/en-us/library/ms257181%28v=vs.80%29.aspx 

How To: Connect to an LDAP Server

 
 
using System;
using System.Net;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Security.Permissions;

namespace ConnectLDAP
{
    [DirectoryServicesPermission(SecurityAction.LinkDemand, Unrestricted = true)]

    public class LDAPConnect 
    {
        // static variables used throughout the example
        static LdapConnection ldapConnection;
        static string  ldapServer;
        static NetworkCredential credential;
        static string targetOU; // dn of an OU. eg: "OU=sample,DC=fabrikam,DC=com"

        public static void Main(string[] args)
        {
            try
            {
                GetParameters(args);  // Get the Command Line parameters

                // Create the new LDAP connection
                ldapConnection = new LdapConnection(ldapServer);        
                ldapConnection.Credential = credential;
                Console.WriteLine("LdapConnection is created successfully.");
            }
            catch (Exception e)
            {
                Console.WriteLine("\r\nUnexpected exception occured:\r\n\t" + e.GetType() + ":" + e.Message);
            }
        }

        static void GetParameters(string[] args)
        {
            // When running: ConnectLDAP.exe <ldapServer> <user> <pwd> <domain> <targetOU>

            if (args.Length != 5)
            {
                Console.WriteLine("Usage: ConnectLDAP.exe <ldapServer> <user> <pwd> <domain> <targetOU>");
                Environment.Exit(-1);// return an error code of -1
            }

            // test arguments to insure they are valid and secure

            // initialize variables
            ldapServer = args[0];
            credential = new NetworkCredential(args[1], args[2], args[3]);
            targetOU = args[4];
        }
    }
}

Thursday, August 14, 2014

Oracle PL/SQL - Proof CASE statement acts like old school C language switch statement with break

select (CASE WHEN FIRST_NAME = 'LUKE' THEN 'A'
                      WHEN LAST_NAME = 'SKYWALKER' THEN 'B'
                      ELSE 'X'
           END) MYRESULT
from dbo.person where person_id = 123


select (CASE WHEN LAST_NAME = 'SKYWALKER' THEN 'A'
                      WHEN FIRST_NAME = 'LUKE' THEN 'B'
                      ELSE 'X'
           END) MYRESULT
from dbo.person where person_id = 123

select (CASE WHEN FIRST_NAME = 'LUKE' THEN 'A'
                      WHEN FIRST_NAME = 'LUKE' THEN 'B'
                      WHEN FIRST_NAME = 'LUKE' THEN 'C'
                      ELSE 'X'
           END) MYRESULT
from dbo.person where person_id = 123




All results are A, so that means its like a C-language switch statement with break.


Monday, August 11, 2014

REPORTS_FINAL


package report_finals;

import java.util.Set;
import java.util.Hashtable;
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
{
    static String dev_db = "jdbc:oracle:thin:@10.22.33.44:1521:blahA";
    static String prod_db = "jdbc:oracle:thin:@10.33.44.55:1521:blahB";
    static String login = "login";
    static String password = "password";
   
    static String input_file_name = null;
    static String output_file_name = null;
   
    static int database_choice = 0;
    static String chosen_db = null;
   
    public static int ReadHumanUserInput()
    {
        int status = 0;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try
        {
            isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);
           
            while (true)
            {
                System.out.println("Please enter 1=V3PRODA1  2=V3UATA");
                String str = br.readLine();
               
                try
                {
                    database_choice = Integer.valueOf(str).intValue();
                }
                catch (NumberFormatException nfe)
                {
                    System.out.println("ERROR: PLEASE TYPE 1 OR 2 FOR CHOICE OF DATABASE AND THEN PRESS ENTER");
                    continue;
                }
               
                if (database_choice != 1 && database_choice != 2)
                {
                    System.out.println("ERROR: DATABASE_CHOICE MUST BE 1 OR 2");
                    continue;
                }
                else
                    break;
            }
           
            if (database_choice == 1)
            {
                chosen_db = prod_db;
                System.out.println("V3PRODA1 = " + chosen_db);
            }
            else
            {
                chosen_db = dev_db;
                System.out.println("V3UATA = " + chosen_db);
            }
           
            while (true)
            {
                System.out.println("Please enter input file name:");
                String str = br.readLine();
               
                if (str.length() == 0)
                {
                    System.out.println("ERROR: INPUT FILE NAME MUST NOT BE BLANK");
                    continue;
                }
                else
                {
                    input_file_name = str;
                    break;
                }
            }
            System.out.println("INPUT_FILE_NAME = " + input_file_name);
           
            while (true)
            {
                System.out.println("Please enter base output file name:");
                String str = br.readLine();
               
                if (str.length() == 0)
                {
                    System.out.println("ERROR: OUTPUT FILE NAME MUST NOT BE BLANK");
                    continue;
                }
                else
                {
                    output_file_name = str;
                    break;
                }
            }
            System.out.println("OUTPUT_FILE_NAME = " + output_file_name);
           
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("ReadHumanUserInput ERROR: Caught exception");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                if (br != null)
                    br.close();
            }
            catch (Exception ex)
            {
                System.out.println("ReadHumanUserInput ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//ReadHumanUserInput
   
    /***
    public static int ReadInputFile(ArrayDeque<String> ssn_queue)
    {
        int status        = 0;
        FileReader fr     = null;
        BufferedReader br = null;
        try
        {
            try
            {
                fr = new FileReader("tab_delimit_test.txt");
            }
            catch (FileNotFoundException e)
            {
                throw new Exception("ReadInputFile ERROR: Can not find input tab delimitted text file!");
            }
            System.out.println("ReadInputFile: Found input tab delimitted text 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 ERROR:");
                    System.out.println(ssn_str);
                    System.out.println("MYLINE ERROR:");
                    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 ReadInputFile_SSN_ONLY(ArrayDeque<String> ssn_queue)
    {
        int status        = 0;
        FileReader fr     = null;
        BufferedReader br = null;
        try
        {
            try
            {
                fr = new FileReader(input_file_name);
            }
            catch (FileNotFoundException e)
            {
                String tempstr = String.format("ReadInputFile_SSN_ONLY ERROR: Can not find input tab delimmited text file with name %s!", input_file_name);
                throw new Exception(tempstr);
            }
            System.out.println("ReadInputFile_SSN_ONLY: Found input tab delimitted text file");

            br = new BufferedReader(fr);
            String myline;
            int datalinecount = 0;
            Boolean has_column_header = false;
       
            myline = br.readLine();
            while (myline != null)
            {
                datalinecount++;
           
                String ssn_str    = myline.trim();
               
                //validate ssn string
                if (ssn_str.length() == 0)
                {
                    System.out.println("ReadInputFile_SSN_ONLY: Ignoring blank line of no SSN");
                }
                else if (ssn_str.length() != 11 && ssn_str.length() != 9)
                {
                    if (datalinecount == 1)
                    {
                        System.out.println("Assuming 1st line is not data but column header, 1st line = " + ssn_str);
                        has_column_header = true;
                    }
                    else
                    {
                        System.out.println("SSN_STR ERROR:");
                        System.out.println(ssn_str);
                        System.out.println("MYLINE ERROR:");
                        System.out.println(myline);
                        throw new Exception("ReadInputFile ERROR: Found a ssn string not length 9 or 11!");
                    }
                }
                else if (ssn_str.length() == 9)
                {
                    String ssn_final = ssn_str;
                    //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_SSN_ONLY ERROR: one of the 9 length 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_SSN_ONLY ERROR: caught exception trying to add 9 length ssn to ssn_queue!");
                    }
                }
                else if (ssn_str.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_SSN_ONLY ERROR: Dashes in ssn 11 length 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_SSN_ONLY ERROR: one of the 11 length 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_SSN_ONLY ERROR: caught exception trying to add to ssn_queue from 11 length ssn!");
                    }
                }
               
                myline = br.readLine();
            }//while myline
           
            if (has_column_header)
                datalinecount--;
           
            if (datalinecount == ssn_queue.size())
                System.out.println(String.format("ReadInputFile_SSN_ONLY: ssn_queue size = datalinecount = %d", datalinecount));
            else
            {
                throw new Exception("ReadInputFile_SSN_ONLY ERROR: ssn_queue size != datalinecount");
            }
            System.out.println("ReadInputFile_SSN_ONLY: Read all of input text csv file");
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("ReadInputFile_SSN_ONLY 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_SSN_ONLY ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//ReadInputFile_SSN_ONLY
   
   
    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(chosen_db, login, password);
            }
            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");
               
                int mycount = ssn_queue.size();
                for (int ii=0; ii < mycount; 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";
               
                java.util.Date wh_start = new java.util.Date();
                System.out.println("WH STOPWATCH START = " + wh_start.toString());
               
                stmt.execute(wh_table_str);
               
                java.util.Date wh_end = new java.util.Date();
                System.out.println("WH STOPWATCH END = " + wh_end.toString());
               
                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 ";
               
                java.util.Date ph_start = new java.util.Date();
                System.out.println("PH STOPWATCH START = " + ph_start.toString());
               
                stmt.execute(ph_table_str);
               
                java.util.Date ph_end = new java.util.Date();
                System.out.println("PH STOPWATCH END = " + ph_end.toString());
               
                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 CreateWHOutputFiles()
    {
        //**************************************************************
        //Query our WH_OUTPUT_TEMP_TABLE result table
        //to make WH output file.
        //**************************************************************
        Connection     connect = null;
        Statement      stmt = null;
        ResultSet      rs = null;
        PersonNameSSN  mymap = new PersonNameSSN();
       
        StringBuilder  column_header = new StringBuilder();
        StringBuilder  big_file      = new StringBuilder();
       
       
        int status = 0;
        try
        {
            connect = DriverManager.getConnection(chosen_db, login, password);
            String query_wh = "SELECT * FROM WH_OUTPUT_TEMP_TABLE";
            stmt = connect.createStatement();
            rs = stmt.executeQuery(query_wh);
           
            String[]       field_name = {"NAME",
                                         "SSN",
                                         "EMPLOYER_NAME",
                                         "BILLING_LOCATION_NAME",
                                         "REPORT_PERIOD_START",
                                         "EARNING_PERIOD_START_DATE",
                                         "EARNING_PERIOD_END_DATE",
                                         "WH_RELEASE_STATUS",
                                         "PAY_CODE",
                                         "PAYMENT_DATE",
                                         "BASE_PAY",
                                         "GROSS_PAY",
                                         "REG_PAY",
                                         "VAC_PAY",
                                         "RETRO_PAY_TYPE",
                                         "RETRO_PAY",
                                         "WC_PAY",
                                         "SAB_LV_PAY",
                                         "OTHER_PAY",
                                         "NORMAL_AS",
                                         "ADDL_AS",
                                         "DIFF_PAY_RECURRING",
                                         "DIFF_PAY_NON_RECURRING",
                                         "NUM_HOURS_WORKED",
                                         "CALCULATED_DAYS",
                                         "FTE",
                                         "PAY_RATE",
                                         "ELIG_COMP",
                                         "GROUP_CODE",
                                         "CLASS_CODE"
                                        };
           
            for (int ii=0; ii < field_name.length; ii++)
            {
                column_header.append(field_name[ii]);
               
                if (ii != (field_name.length - 1))
                    column_header.append("\t");
            }  
            column_header.append(System.lineSeparator());
           
            int linecount = 0;
            String name;
            String namessn;
            while (rs.next())
            {
                linecount++;
                StringBuilder tempsb = new StringBuilder();
               
                //Write to tempsb
                for (int ii=0; ii < field_name.length; ii++)
                {
                    if (rs.getString(field_name[ii]) == null)
                        tempsb.append("");
                    else
                        tempsb.append(rs.getString(field_name[ii]));
                   
                    if (ii != (field_name.length - 1))
                        tempsb.append('\t');
                }
               
                //Write to big_file
                big_file.append(tempsb.toString());
                big_file.append(System.lineSeparator());
               
                //Name + SSN code for separate files
                name    = rs.getString("NAME");
                namessn = rs.getString("NAME") + rs.getString("SSN");
                mymap.Add(name, namessn, tempsb.toString());
            }

            //write big file
            File           myfile = null;
            FileWriter     fw = null;
            String outfilename = String.format("%s_WH_OUTPUT_%drows.txt", output_file_name, linecount);
            myfile = new File(outfilename);
            if (myfile.exists())
            {
                System.out.println("CreateWHOutputFiles: WH OUTPUT file exists");
                Boolean success_delete = myfile.delete();
                if (success_delete)
                    System.out.println("CreateWHOutputFiles: WH OUTPUT file successfully deleted");
                else
                    System.out.println("CreateWHOutputFiles: WH OUTPUT file failed on delete!");
            }

            Boolean success_create = myfile.createNewFile();
            if (success_create)
                System.out.println("CreateWHOutputFiles: WH OUTPUT file successfully created");
            else
                System.out.println("CreateWHOutputFiles: WH OUTPUT file failed on create!");

            fw = new FileWriter(myfile);
            fw.write(column_header.toString());
            fw.write(big_file.toString());
            fw.flush();
            fw.close();
            System.out.println(String.format("CreateWHOutputFiles: WH OUTPUT file wrote %d lines", linecount));
           
            //write person files
            int person_dump_status = mymap.DumpFiles(output_file_name, column_header.toString());
            if (person_dump_status != 0)
                throw new Exception("CreateWHOutputFiles THROWING EXCEPTION TO CALLER OF mymap.DumpFiles");
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("CreateWHOutputFiles 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();
            }
            catch (Exception ex)
            {
                System.out.println("CreateWHOutputFiles ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//CreateWHOutputFiles
   
    public static int CreatePHOutputFiles()
    {
        //**************************************************************
        //Query PH_OUTPUT_TEMP_TABLE result table
        //to make PH output file.
        //**************************************************************
        Connection     connect = null;
        Statement      stmt = null;
        ResultSet      rs = null;
        PersonNameSSN  mymap = new PersonNameSSN();
       
        StringBuilder  column_header = new StringBuilder();
        StringBuilder  big_file      = new StringBuilder();
       
        String[]       field_name = {"NAME",
                                     "SSN",
                                     "START_DATE",
                                     "STOP_DATE",
                                     "CRED",
                                     "HCOMP",
                                     "ACOMP",
                                     "CCOMP",
                                     "TRANS_TYPE",
                                     "ELIG_COMP",
                                     "JOB_CLASS",
                                     "VAC_PAY",
                                     "FORFEITED"};
       
        int status = 0;
        try
        {
            connect = DriverManager.getConnection(chosen_db, login, password);
            String query_wh = "SELECT * FROM PH_OUTPUT_TEMP_TABLE";
            stmt = connect.createStatement();
            rs = stmt.executeQuery(query_wh);
             
            for (int ii=0; ii < field_name.length; ii++)
            {
                column_header.append(field_name[ii]);
                if (ii != (field_name.length - 1))
                    column_header.append("\t");
            }  
            column_header.append(System.lineSeparator());
           
            int linecount = 0;
            String name;
            String namessn;
            while (rs.next())
            {
                linecount++;
                StringBuilder tempsb = new StringBuilder();
               
                //write to tempsb
                for (int ii=0; ii < field_name.length; ii++)
                {
                    if (rs.getString(field_name[ii]) == null)
                        tempsb.append("");
                    else
                        tempsb.append(rs.getString(field_name[ii]));
                   
                    if (ii != (field_name.length - 1))
                        tempsb.append('\t');
                }
               
                //Write to big_file
                big_file.append(tempsb.toString());
                big_file.append(System.lineSeparator());
               
                //Name + SSN code for separate files
                name    = rs.getString("NAME");
                namessn = rs.getString("NAME") + rs.getString("SSN");
                mymap.Add(name, namessn, tempsb.toString());
            }

            //write big file
            String outfilename = String.format("%s_PH_OUTPUT_%drows.txt", output_file_name, linecount);
            File myfile = new File(outfilename);
            if (myfile.exists())
            {
                System.out.println("CreatePHOutputFiles: PH OUTPUT file exists");
                Boolean success_delete = myfile.delete();
                if (success_delete)
                    System.out.println("CreatePHOutputFiles: PH OUTPUT file successfully deleted");
                else
                    System.out.println("CreatePHOutputFiles: PH OUTPUT file failed on delete!");
            }
            Boolean success_create = myfile.createNewFile();
            if (success_create)
                System.out.println("CreatePHOutputFiles: PH OUTPUT file successfully created");
            else
                System.out.println("CreatePHOutputFiles: PH OUTPUT file failed on create!");
           
            FileWriter fw = new FileWriter(myfile);
            fw.write(column_header.toString());
            fw.write(big_file.toString());
            fw.flush();
            fw.close();
            System.out.println(String.format("CreatePHOutputFiles: PH OUTPUT file wrote %d lines", linecount));
           
            //write person files
            int person_dump_status = mymap.DumpFiles(output_file_name, column_header.toString());
            if (person_dump_status != 0)
                throw new Exception("CreatePHOutputFiles THROWING EXCEPTION TO CALLER OF mymap.DumpFiles");
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("CreatePHOutputFiles 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();
            }
            catch (Exception ex)
            {
                System.out.println("CreatePHOutputFiles ERROR: Caught exception trying to close out");
                System.out.println(ex.getMessage());
                ex.printStackTrace();
            }
        }
        return status;
    }//CreatePHOutputFiles
   
    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 = ReadHumanUserInput();
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from ReadHumanUserInput EXITING PROGRAM");
            return;
        }
       
        status = ReadInputFile_SSN_ONLY(ssn_queue);
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from ReadInputFile_SSN_ONLY EXITING PROGRAM");
            return;
        }
       
        status = CreateTemporaryTables(ssn_queue);
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from CreateTemporaryTables EXITING PROGRAM");
            return;
        }
       
        status = CreateWHOutputFiles();
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from CreateWHOutputFiles EXITING PROGRAM");
            return;
        }
       
        status = CreatePHOutputFiles();
        if (status != 0)
        {
            System.out.println("main ERROR: Bad status from CreatePHOutputFiles EXITING PROGRAM");
            return;
        }
       
        System.out.println("DONE");
    }//main
}//class REPORT_FINALS











package report_finals;

import java.io.FileWriter;
import java.util.Hashtable;
import java.util.Set;

public class PersonNameSSN
{
    //Key   = name
    //Value = count
    private Hashtable <String, Integer> name_count;
       
    //Key   = name + actual ssn
    //Value = row count
    private Hashtable <String, Integer> name_ssn_rowcount;
       
    //Key   = name + actual ssn
    //Value = person filename base (name, ssnmask)
    private Hashtable <String, String>  name_ssn_maskname;
       
    //Key = name + actual ssn
    //Value = StringBuilder
    private Hashtable <String, StringBuilder>  name_ssn_strbuild;
   
    public PersonNameSSN()
    {
        name_count        = new Hashtable<String, Integer>();
        name_ssn_rowcount = new Hashtable<String, Integer>();
        name_ssn_maskname = new Hashtable<String, String>();
        name_ssn_strbuild = new Hashtable<String, StringBuilder>();
    }
   
    public void Add(String name, String namessn, String data_row_str)
    {
        if (name_ssn_rowcount.containsKey(namessn))
        {
            Integer rowcount = name_ssn_rowcount.get(namessn);
            rowcount++;
            name_ssn_rowcount.replace(namessn, rowcount);

            name_ssn_strbuild.get(namessn).append(data_row_str);
            name_ssn_strbuild.get(namessn).append(System.lineSeparator());
        }
        else
        {
            Integer maskcnt;
            if (name_count.containsKey(name))
            {
                maskcnt = name_count.get(name);
                maskcnt++;
                name_count.replace(name, maskcnt);
            }
            else
            {
                maskcnt = 1;
                name_count.put(name, maskcnt);
            }

            name_ssn_rowcount.put(namessn, 1);

            String maskname = String.format("%s_SSN%d", name, maskcnt);
            maskname = maskname.replace(',',  '_');
            maskname = maskname.replace(' ',  '_');
            maskname = maskname.replace("__", "_");
            name_ssn_maskname.put(namessn, maskname);

            name_ssn_strbuild.put(namessn, new StringBuilder());
            name_ssn_strbuild.get(namessn).append(data_row_str);
            name_ssn_strbuild.get(namessn).append(System.lineSeparator());
        }
    }//Add
   
    public int DumpFiles(String output_file_name, String column_header_str)
    {
        int status = 0;
        try
        {
            Set<String> set_namessn = name_ssn_rowcount.keySet();
            int keycount = set_namessn.size();
            Object[] keys = set_namessn.toArray();
            for (int ii=0; ii < keycount; ii++)
            {
                String mynamessn = (String)keys[ii];
                String personfilename = String.format("%s_%s_%drows.txt", output_file_name, name_ssn_maskname.get(mynamessn), name_ssn_rowcount.get(mynamessn));
                FileWriter personfile = new FileWriter(personfilename, true);
                personfile.write(column_header_str);
                personfile.write(name_ssn_strbuild.get(mynamessn).toString());
                personfile.flush();
                personfile.close();
            }
        }
        catch (Exception ex)
        {
            status = -1;
            System.out.println("PersonNameSSN.DumpFiles ERROR: CAUGHT EXCEPTION!");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
        return status;
    }//DumpFiles
}//PersonNameSSN