1. import org.apache.commons.io.input.InputUtils;
  2. import org.apache.commons.io.output.StringOutputStream;
  3. import java.io.IOException;
  4. import java.nio.charset.StandardCharsets;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. public class HtmlDiff {
  8. /**
  9. * Diffs two HTML strings with a timeout.
  10. *
  11. * @param html1 The first HTML string.
  12. * @param html2 The second HTML string.
  13. * @param timeoutMillis The timeout in milliseconds.
  14. * @return A map containing the differences. Returns an empty map if no differences are found or an error occurs.
  15. */
  16. public static Map<String, String> diffHtml(String html1, String html2, int timeoutMillis) {
  17. Map<String, String> differences = new HashMap<>();
  18. if (html1 == null || html2 == null) {
  19. return differences; // Return empty map for null inputs
  20. }
  21. try {
  22. // Use a timeout in the I/O operations
  23. StringOutputStream outputStream = new StringOutputStream();
  24. try {
  25. //Write html1 to output stream
  26. outputStream.write(html1.getBytes(StandardCharsets.UTF_8));
  27. String streamContent = outputStream.toString(StandardCharsets.UTF_8);
  28. // Compare the HTML strings. Simple string comparison for now.
  29. if (!html1.equals(html2)) {
  30. differences.put("html1", html1);
  31. differences.put("html2", html2);
  32. }
  33. } catch (IOException e) {
  34. //Handle the exception - timeout or other I/O error
  35. System.err.println("Error during diff: " + e.getMessage());
  36. return differences;
  37. } finally {
  38. outputStream.close();
  39. }
  40. } catch (Exception e) {
  41. System.err.println("Exception during diff: " + e.getMessage());
  42. return differences;
  43. }
  44. return differences;
  45. }
  46. public static void main(String[] args) {
  47. // Example usage
  48. String html1 = "<html><body><h1>Hello</h1><p>World</p></body></html>";
  49. String html2 = "<html><body><h1>Hello</h1><p>Updated World</p></body></html>";
  50. Map<String, String> diff = diffHtml(html1, html2, 5000); // 5 second timeout
  51. if (diff.isEmpty()) {
  52. System.out.println("No differences found.");
  53. } else {
  54. System.out.println("Differences found:");
  55. for (Map.Entry<String, String> entry : diff.entrySet()) {
  56. System.out.println(entry.getKey() + ": " + entry.getValue());
  57. }
  58. }
  59. }
  60. }

Add your comment