import org.apache.commons.io.input.InputUtils;
import org.apache.commons.io.output.StringOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class HtmlDiff {
/**
* Diffs two HTML strings with a timeout.
*
* @param html1 The first HTML string.
* @param html2 The second HTML string.
* @param timeoutMillis The timeout in milliseconds.
* @return A map containing the differences. Returns an empty map if no differences are found or an error occurs.
*/
public static Map<String, String> diffHtml(String html1, String html2, int timeoutMillis) {
Map<String, String> differences = new HashMap<>();
if (html1 == null || html2 == null) {
return differences; // Return empty map for null inputs
}
try {
// Use a timeout in the I/O operations
StringOutputStream outputStream = new StringOutputStream();
try {
//Write html1 to output stream
outputStream.write(html1.getBytes(StandardCharsets.UTF_8));
String streamContent = outputStream.toString(StandardCharsets.UTF_8);
// Compare the HTML strings. Simple string comparison for now.
if (!html1.equals(html2)) {
differences.put("html1", html1);
differences.put("html2", html2);
}
} catch (IOException e) {
//Handle the exception - timeout or other I/O error
System.err.println("Error during diff: " + e.getMessage());
return differences;
} finally {
outputStream.close();
}
} catch (Exception e) {
System.err.println("Exception during diff: " + e.getMessage());
return differences;
}
return differences;
}
public static void main(String[] args) {
// Example usage
String html1 = "<html><body><h1>Hello</h1><p>World</p></body></html>";
String html2 = "<html><body><h1>Hello</h1><p>Updated World</p></body></html>";
Map<String, String> diff = diffHtml(html1, html2, 5000); // 5 second timeout
if (diff.isEmpty()) {
System.out.println("No differences found.");
} else {
System.out.println("Differences found:");
for (Map.Entry<String, String> entry : diff.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
}
Add your comment