/* Andreas Maeurer
 * modified: 10/03/2016
 * 
 * Requirements:
    * This file uses the JavaMail API which can be downloaded from here:
    * https://java.net/projects/javamail/pages/Home#Download_JavaMail_Release
    * and I think also from here:
    * https://java.net/projects/javamail/pages/Home
    *  
    *     So download the "javax.mail.jar" file.
    *     then "Set your CLASSPATH to include the "javax.mail.jar" file obtained from
    *        the download, as well as the current directory."
    *     you would do this by running the command:
    *         export CLASSPATH=$CLASSPATH:/home/andreas/csIch/javax.mail.jar:.
    *     obviously in your case you would change the path to where ever you are keeping the file...
 *
 * Notes:
    *    I haven't looked into importing the JavaMail API into Eclipse.
    *     I ran the export CLASSPATH=$CLASSPATH:/home/andreas/csIch/javax.mail.jar:. command in the linux command line and 
    *     I had to run it again inside of Geany for this to work in Geany.
    *     At this time this file works for Yahoo Email Addresses as senders only.  Gmail uses an API for added security 
    *     so it requires some more work to include a way for sending from Gmail
 
 * Scope:
     * The purpose of AlertMeToChangeOnWebpage.java is to:
     *     Download the html (or other code) of a webpage,
     *     store this code in a file
     *     compare this file to the previous file (if there is no previous file, then the downloaded file is the first file...)
     *     if the file is different, then send out an email to let the User know that the webpage has changed
     * 
     *     Emails have their own timestamps and most of us are alerted on our SmartPhone when we receive an email.  This fact
     *     provides the usefulness of this .java file.
     * 
     * For now all I want to monitor is the course webpage.
     * 
     * In the future I intend to let this .java file run from a Shell Script on my desktop PC every half hour during the hours between 7am and 9pm 
     * and every hour between the hours 9pm and 7am.  Once a couple of changes of the website have been detected, the time stamp 
     * of the email will let me know what the "busy" hours are.  I will then set the times of day the script runs accordingly.
     * 
     * In the future more thought will be put into how the files should be stored.  How many of the previous files should be kept or deleted
     * whether this should be based on quantity of the files or age of the files...
     * 
     * In the far future it is conceivable that the program may monitor several webpages and let the user know which page has changed etc.
     * 
     * In the far future it is also conceivable that the program may run as an app on a SmartPhone.  Where then the timestamps and Alerts may be 
     * handled differently.
 */


import java.io.*;
import java.net.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class AlertMeToChangeOnWebpage {


   /* adapted from: http://alvinalexander.com/blog/post/java/jget-something-like-wget
    * A simple Java method to provide functionality similar to Wget.
    * 
    * So basically all this method does is download the course html 
    */
 
    public static void javaMethodWget() throws FileNotFoundException {        
        
        String url = "http://www.cs.utep.edu/ofuentes/cs2302.html";

        URL u;
        InputStream is = null;
        DataInputStream dis;
        String s;        
       
        PrintStream ps = new PrintStream("cs2302.html");                //ich

        try {
            u = new URL(url);
            is = u.openStream();
            dis = new DataInputStream(new BufferedInputStream(is));
            while ((s = dis.readLine()) != null) {
                //System.out.println(s);                                //this line prints the .html file to the screen
                ps.println(s);                                            //(ich) this line prints the .html file to the filename.txt
            }
        } catch (MalformedURLException mue) {
            System.err.println("Ouch - a MalformedURLException happened.");
            mue.printStackTrace();
            System.exit(2);
        } catch (IOException ioe) {
            System.err.println("Oops- an IOException happened.");
            ioe.printStackTrace();
            System.exit(3);
        } finally {
            try {
                is.close();
            } catch (IOException ioe) {}
        }       
    }
    
    /* Adapted from: http://stackoverflow.com/questions/1510520/how-to-compare-the-contents-of-two-text-files-and-return-same-content-or-diff
     * 
     * This method puts the "master record" named filename.txt and the fresh downloaded file into strings and compares them
     * It returns true if they are the same.  False if not the same.
     */
    
    public static boolean compareTheTwoFiles() throws java.io.IOException {        
        
        String s1 = "";        
        String s3 = "";        
        String y = "";
        String z = "";
        
        File file1 = new File("cs2302.html");    //let's imagine this is the "recently downloaded file"
        File file2 = new File("filename.txt");  //let's imagine this is the "previous file"

        BufferedReader bfr = new BufferedReader(new FileReader(file1));
        BufferedReader bfr2 = new BufferedReader(new FileReader(file2));

        while ((z = bfr2.readLine()) != null)
            s3 += z;

        while ((y = bfr.readLine()) != null)
            s1 += y;

        System.out.println();

        //System.out.println(s3);

        if (s3.equals(s1)) {
            //System.out.println("Content of both files are same");          //not sure yet if I should leave that in or not
            return true;
        } 
        else {
            //System.out.println("Content of both files are not same");        //not sure yet if I should leave that in or not
            return false;
        }
    }
    
    /*  adapted from: http://stackoverflow.com/questions/11356237/sending-mail-from-yahoo-id-to-other-email-ids-using-javamail-api
     *           
     *     remember to remove own password before sharing code with others...!!!
     * 
     *     This method sends out an Email
     */
     
    public static void sendEmailFromYahoo() {
    
        // Sender's email ID needs to be mentioned
        
        String from = "dermeister7@yahoo.com";                //<--- Sender's Yahoo Email        
        String pass = "XXXXXXXXX";                            //<--- Sender's Password!  //Todo: note that the password here was hardcoded
        // Recipient's email ID needs to be mentioned.        
        //String to = "maeurer2002@yahoo.com";     
        String to = "andreas.maeurer@gmail.com"
        
        String host = "smtp.mail.yahoo.com";

        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.put("mail.smtp.starttls.enable""true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.user", from);
        properties.put("mail.smtp.password", pass);
        properties.put("mail.smtp.port""587");
        properties.put("mail.smtp.auth""true");

        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);

            // Set From: header field of the header.
            message.setFrom(new InternetAddress(from));

            // Set To: header field of the header.
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: header field
            //message.setSubject("This is the Subject Line!");
            message.setSubject("Achtung! There has been a change on the Webpage!!!");  //This is the Subject Line!");

            // Now set the actual message
            //message.setText("This is actual message");
            message.setText("There has been a change to the webpage: http://www.cs.utep.edu/ofuentes/cs2302.html  ");

            // Send message
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
    
    /*  This Method is pretty self expanatory
     * 
     *     The reason it is in here is that I will run this .java file from Bash Shell Script and in the Shell Script I am 
     *     going to pump out this output to text file.  That .txt file will serve as a log documenting what happened when.
     */

    public static void tellMeTheDateAndTime(){        
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        System.out.println(dateFormat.format(cal.getTime()));
    }
    
    public static void main(String[] args) throws FileNotFoundException, java.io.IOException {
        
        javaMethodWget();
        
        boolean resultOfComparison = compareTheTwoFiles();
        
        if (resultOfComparison==true) {
            tellMeTheDateAndTime();
            System.out.println("The two files are equal.");
            System.out.println("No further action is required.");            
        }
        else {
            tellMeTheDateAndTime();
            System.out.println("The two files are NOT equal.");
            System.out.println("An email will be sent out.");
            sendEmailFromYahoo();
        }        
    }
}
Code Formatted by ToGoTutor