import java.io.*;
import java.util.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.security.*;
import com.sun.net.ssl.*;
import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class PostXML
{
    public static void main(String args[])
    {
        try
        {
            PrintWriter logger = null;
            String queryString = "";
            boolean custom = false;
            boolean valid_params = false;
            String password = "";
            String username = "";
            String filename = "";
            String logfile = "";
            String url = "https://test.e-abg.com:443/invoke/wm.tn/receive";
            String buff = "";
            String type = "";
            // for printing current date
            Calendar calendar = new GregorianCalendar();
            
            //parse out args (get username/password/filename)
            if(args != null && args.length > 0)
            {

                for(int r = 0; r < args.length; r++)
                {
                    if((args[r]).equalsIgnoreCase("-p") && ((r + 1) < args.length))
                    {
                        password = args[r + 1];
                        r++;
                        custom = true;
                    } else if((args[r]).equalsIgnoreCase("-u") && ((r + 1) < args.length)) {
                        username = args[r + 1];
                        r++;
                        custom = true;
                    } else if((args[r]).equalsIgnoreCase("-o") && ((r + 1) < args.length)) {
                        logfile = args[r + 1];
                        if(logfile != null)
                        {
                            if(logfile.length() > 1)
                            {
                                if(logfile.substring(0,1).equals("\""))
                                {       logfile = logfile.substring(1); }
                                if(logfile.substring(logfile.length(),logfile.length()).equals("\""))
                                {       logfile = logfile.substring(0, logfile.length() - 1); }
                            }
                            r++;
                            logger = new PrintWriter(new BufferedWriter(new FileWriter(logfile, true)));
                        }
                    } else if((args[r]).equalsIgnoreCase("-f") && ((r + 1) < args.length)) {
                        filename = args[r + 1];
                        if(filename != null)
                        {
                            if(filename.length() > 1)
                            {
                                if(filename.substring(0,1).equals("\""))
                                {       filename = filename.substring(1); }
                                if(filename.substring(filename.length(),filename.length()).equals("\""))
                                {       filename = filename.substring(0, filename.length() - 1); }
                            }
                            r++;
                            valid_params = true;
                        }
                    } else if((args[r]).equalsIgnoreCase("-url") && ((r + 1) < args.length)) {
                        url = args[r + 1];
                        if(url != null)
                        {
                            if(url.length() > 1)
                            {
                                if(url.substring(0,1).equals("\""))
                                {       url = url.substring(1); }
                                if(url.substring(url.length(),url.length()).equals("\""))
                                {       url = url.substring(0, url.length() - 1); }
                            }
                            r++;
                        }
                    } else if((args[r]).equalsIgnoreCase("-type") && ((r + 1) < args.length)) {
                        type = args[r + 1];
                        if(type != null)
                        {
                            if(type.length() > 1)
                            {
                                if(type.substring(0,1).equals("\""))
                                {       type = type.substring(1); }
                                if(type.substring(type.length(),type.length()).equals("\""))
                                {       type = type.substring(0, type.length() - 1); }
                            }
                            r++;
                        }
                    }
                }
            } 
            
                
            // check if all required params passed
            if(!valid_params)
            {
                // print out help and quit
                buff = "usage: java PostXML {-u username} {-p password} -url \"https://url:443/\" -o \"path/logFile\" -f \"path/filename\" -type \"application/EDI; charset=UTF-8\"";
                if(logger != null)
                {   
                    System.out.println(buff);
                    logger.print(buff);
                } else {
                    System.out.println(buff);
                }
                return;
            }
            
            // print out date/time info
            if(logger != null)
            {
                
                
                logger.print("+++++++++++++++++++++++\n");
                logger.print("  Uploading file at " + calendar.get(Calendar.YEAR) + "." + (calendar.get(Calendar.MONTH) + 1) + "." + calendar.get(Calendar.DAY_OF_MONTH) + "  " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND) +"\n");
                logger.print("+++++++++++++++++++++++\n");
            } else {
                System.out.println("Uploading file at " + calendar.get(Calendar.YEAR) + "." + (calendar.get(Calendar.MONTH) + 1) + "." + calendar.get(Calendar.DAY_OF_MONTH) + "  " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND));
            }
            
            // get file contents
            File f = new File(filename);
            if(f != null && f.exists())
            {
                FileReader freader = new FileReader(f);
                BufferedReader fin = new BufferedReader((Reader)freader);
                String line;
                while((line = fin.readLine()) != null)
                {       queryString = queryString + line; }
                fin.close();
            } else {
                // print out error message if file not found
                if(logger != null)
                {
                    buff = "File not found: " + filename;
                    System.out.println(buff);
                    logger.print(buff);
                } else {
                    System.out.println("File not found: " + filename);
                }
                return;
            }
            
            // set authenticator method
            if(custom)
            {   
                // use passed username/password
                Authenticator auth = (Authenticator)new PostXML$Auth(username, password);
                Authenticator.setDefault(auth);
            } else {
                //set interactive password prompt
                Authenticator.setDefault( new PostXML$AuthImpl() );
            }
            
            URL Url = new URL (url);
            
            if(logger != null)
            {   
                buff = "Opening connection to '" + Url + "'\n";
                logger.print(buff);
            } else {
                System.out.println("Opening connection to '" + Url + "'");
            }
            HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Length", String.valueOf(queryString.length()));
            connection.setRequestProperty("Content-Type", type);
            if(!custom) 
            {   connection.setAllowUserInteraction(true); }
            
            // create string to send
            if(logger != null)
            {
                buff = "Posting data in: " + filename + "\nStart of Data ***************************\n";
                logger.print(buff);
                logger.print(queryString);
                buff = "\nEnd of Data******************************\n";
                logger.print(buff);
            } else {
                System.out.println("Posting data in: " + filename + " (" + queryString.length() + " characters)");
            }
            BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
            // send file
            out.write(queryString.getBytes());
            // flush the stream
            out.flush();
            // close the post stream
            out.close();
            
            // read the response
            if(logger != null)
            {
                buff = "Start of Response ************************\n";
                logger.print(buff);
                BufferedReader cin = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while((line = cin.readLine()) != null)
                {       
                    System.out.println(line); 
                }
                cin.close();
                buff = "\nEnd of Response ************************\n";
                logger.print(buff);
            }
            
            if(logger != null)
            {
                logger.print("Response code: " + connection.getResponseCode() + " " + connection.getResponseMessage() + "\n\n\n");
                logger.flush();
                logger.close();
            } else {
                System.out.println("Response code: " + connection.getResponseCode() + " " + connection.getResponseMessage());
            }
            
            // close the connection to the server
            connection.disconnect();
            System.out.println("Connection closed.");
            System.exit(0);
        } catch (Exception e) {
            System.out.println("Error sending data to server: " + e.toString());
        }
        return;
    }
    
    private static class PostXML$Auth extends Authenticator
    {
        private String u = "";
        private String p = "";
        
        public PostXML$Auth(String user, String pass)
        {
            super();
            u = user;
            p = pass;
        }
        
        protected PasswordAuthentication getPasswordAuthentication()
        {   return new PasswordAuthentication (u, (p).toCharArray()); }
    }
    
    public static class PostXML$AuthImpl extends Authenticator
    {
        protected PasswordAuthentication getPasswordAuthentication()
        {
            JTextField username = new JTextField();
            JTextField password = new JPasswordField();
            JPanel panel = new JPanel(new GridLayout(2,2));
            panel.add(new JLabel("User Name"));
            panel.add(username);
            panel.add(new JLabel("Password") );
            panel.add(password);
            int option = JOptionPane.showConfirmDialog(null, new Object[] {
                "Site: "+getRequestingHost(),
                "Realm: "+getRequestingPrompt(), panel},
                "Enter Network Password",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if ( option == JOptionPane.OK_OPTION )
            {
                String user = username.getText();
                char pass[] = password.getText().toCharArray();
                return new PasswordAuthentication(user, pass);
            } else {
                return null;
            }
        }
    }
}