/* Author: Julie Romm * Course: COM3336 * Professor: Karl Lieberherr * Homework 3, part 2 */ /* File: URLThread.java * Classes implemented: URLThread * * Purpose: * This class attempts to access the URL object constructed with urlpath. * Once the connections is successfully made, the HTML source code of the * page is writen into a file. Also, the run method of this class * instantiate URLDiffThread object, and starts its run() method, * which determines whether the current version of this page differs * from the previous one. */ import java.io.*; import java.util.*; import java.net.*; public class URLThread extends Thread { private String urlpath; private boolean status = false; private URL url; private BufferedReader br; private BufferedWriter bw; private String filename; private File oldfile; private File newfile; private Process p; private Runtime r; private String line; //constructor public URLThread (String urlpath) { this.urlpath = urlpath; filename = urlpath.substring(7); oldfile = new File(filename + ".old"); newfile = new File(filename + ".new"); } //public accessor public boolean getStatus() { return status; } public synchronized void run() { //System.out.println("URLThread: starting run()"); try {url = new URL(urlpath);} catch (MalformedURLException e){}; //The following fragment of code renames //the new file into old file r = Runtime.getRuntime(); try {p = r.exec("mv " + newfile.toString() + " " + oldfile.toString());} catch (IOException e) { System.err.println("URLThread: Error: " + e); } try { br = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream())); bw = new BufferedWriter(new FileWriter(filename + ".new")); } catch (IOException e){}; //access the url and retrieve the html source code of the page while (br == null) { try { br = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream())); } catch (IOException e){}; if (isInterrupted()) { status = false; return; } } //write the source code of the page into a file String line; try { while ((line = br.readLine()) != null) { //System.out.println(line); bw.write(line + "\n"); }//while bw.close(); br.close(); } //try catch (IOException e){}; System.out.println("URLThread: successfully retrieved " + urlpath); //diff it with the previous version of this page URLDiffThread dm = new URLDiffThread(filename); dm.start(); status = true; }//run }//URLThread