import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HtmlCache {
private final Map<String, String> cache = new HashMap<>(); // Cache to store HTML content
private final int cacheSizeLimit; // Maximum number of HTML documents to cache
public HtmlCache(int cacheSizeLimit) {
this.cacheSizeLimit = cacheSizeLimit;
}
/**
* Retrieves the HTML content for a given URL from the cache.
* If the content is not in the cache, it fetches it from the source and caches it.
*
* @param url The URL of the HTML document.
* @return The HTML content as a string.
* @throws IOException If an error occurs during fetching or caching.
*/
public String getHtml(String url) throws IOException {
if (cache.containsKey(url)) {
System.out.println("Retrieving from cache: " + url);
return cache.get(url);
}
System.out.println("Fetching from source: " + url);
String html = fetchHtml(url); // Fetch HTML content from the source
cache.put(url, html); // Cache the fetched HTML content
// Evict the least recently used entry if the cache is full
if (cache.size() > cacheSizeLimit) {
evictLeastRecentlyUsed();
}
return html;
}
private String fetchHtml(String url) throws IOException {
// Simulate fetching HTML from a source (e.g., a web server)
// Replace this with your actual HTTP request implementation
return "<html><body><h1>HTML Content for " + url + "</h1></body></html>";
}
private void evictLeastRecentlyUsed() {
if (cache.isEmpty()) {
return; // Nothing to evict
}
String oldestKey = null;
for (String key : cache.keySet()) {
if (oldestKey == null || key.compareTo(oldestKey) < 0) {
oldestKey = key;
}
}
cache.remove(oldestKey); // Remove the least recently used entry
}
}
Add your comment