1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class HtmlCache {
  7. private final Map<String, String> cache = new HashMap<>(); // Cache to store HTML content
  8. private final int cacheSizeLimit; // Maximum number of HTML documents to cache
  9. public HtmlCache(int cacheSizeLimit) {
  10. this.cacheSizeLimit = cacheSizeLimit;
  11. }
  12. /**
  13. * Retrieves the HTML content for a given URL from the cache.
  14. * If the content is not in the cache, it fetches it from the source and caches it.
  15. *
  16. * @param url The URL of the HTML document.
  17. * @return The HTML content as a string.
  18. * @throws IOException If an error occurs during fetching or caching.
  19. */
  20. public String getHtml(String url) throws IOException {
  21. if (cache.containsKey(url)) {
  22. System.out.println("Retrieving from cache: " + url);
  23. return cache.get(url);
  24. }
  25. System.out.println("Fetching from source: " + url);
  26. String html = fetchHtml(url); // Fetch HTML content from the source
  27. cache.put(url, html); // Cache the fetched HTML content
  28. // Evict the least recently used entry if the cache is full
  29. if (cache.size() > cacheSizeLimit) {
  30. evictLeastRecentlyUsed();
  31. }
  32. return html;
  33. }
  34. private String fetchHtml(String url) throws IOException {
  35. // Simulate fetching HTML from a source (e.g., a web server)
  36. // Replace this with your actual HTTP request implementation
  37. return "<html><body><h1>HTML Content for " + url + "</h1></body></html>";
  38. }
  39. private void evictLeastRecentlyUsed() {
  40. if (cache.isEmpty()) {
  41. return; // Nothing to evict
  42. }
  43. String oldestKey = null;
  44. for (String key : cache.keySet()) {
  45. if (oldestKey == null || key.compareTo(oldestKey) < 0) {
  46. oldestKey = key;
  47. }
  48. }
  49. cache.remove(oldestKey); // Remove the least recently used entry
  50. }
  51. }

Add your comment