import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class HTMLMonitor {
private static final ConcurrentHashMap<String, MonitorResult> monitorResults = new ConcurrentHashMap<>();
public static void main(String[] args) {
// Example usage: Monitor a few URLs
monitor("https://www.example.com");
monitor("https://www.google.com");
monitor("https://invalid-url.example"); // Example of an invalid URL
}
/**
* Monitors an HTML document at the given URL.
*
* @param url The URL of the HTML document to monitor.
*/
public static void monitor(String url) {
try {
URL absoluteUrl = new URL(url); // Create a URL object
monitorDocument(absoluteUrl.toString());
} catch (MalformedURLException e) {
logError("Invalid URL: " + url, e);
}
}
/**
* Monitors a single HTML document.
*
* @param url The URL of the HTML document.
*/
public static void monitorDocument(String url) {
try {
long startTime = System.currentTimeMillis();
String response = fetchHtmlDocument(url);
long endTime = System.currentTimeMillis();
MonitorResult result = new MonitorResult(url, response, endTime - startTime);
monitorResults.put(url, result);
// Further processing of the HTML content could be done here (e.g., parsing).
System.out.println("Monitored: " + url + " - Duration: " + (endTime - startTime) + "ms");
} catch (IOException e) {
logError("Error monitoring document: " + url, e);
}
}
/**
* Fetches the HTML document from the given URL.
* @param url The URL to fetch
* @return The HTML content as a string.
* @throws IOException if an error occurs during the fetch.
*/
private static String fetchHtmlDocument(String url) throws IOException {
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000); // Set a timeout of 5 seconds
connection.setConnectTimeout(5000);
connection.getInputStream(); // Force connection
return connection.getText();
}
/**
* Logs an error message to the console.
*
* @param message The error message.
* @param e The exception that caused the error.
*/
private static void logError(String message, Exception e) {
System.err.println("ERROR: " + message);
e.printStackTrace();
}
/**
* Inner class to store the results of monitoring a document.
*/
static class MonitorResult {
String url;
String htmlContent;
long duration;
public MonitorResult(String url, String htmlContent, long duration) {
this.url = url;
this.htmlContent = htmlContent;
this.duration = duration;
}
}
}
Add your comment