View Javadoc
1   package com.ljs.ootp.extract.html.loader;
2   
3   import com.google.common.base.Throwables;
4   import com.google.common.cache.CacheBuilder;
5   import com.google.common.cache.CacheLoader;
6   import com.google.common.cache.LoadingCache;
7   import java.util.concurrent.ExecutionException;
8   import org.jsoup.nodes.Document;
9   
10  /**
11   *
12   * @author lstephen
13   */
14  public final class InMemoryCachedLoader implements PageLoader {
15  
16      private static final Integer MAXIMUM_CACHE_SIZE = 200;
17  
18      private final LoadingCache<String, Document> cache;
19  
20      private InMemoryCachedLoader(final PageLoader wrapped) {
21          cache = CacheBuilder
22              .newBuilder()
23              .maximumSize(MAXIMUM_CACHE_SIZE)
24              .initialCapacity(MAXIMUM_CACHE_SIZE)
25              .build(new CacheLoader<String, Document>() {
26                  @Override
27                  public Document load(String key) {
28                      return wrapped.load(key);
29                  }
30              });
31      }
32  
33      @Override
34      public Document load(String url) {
35          try {
36              return cache.get(url);
37          } catch (ExecutionException e) {
38              throw Throwables.propagate(e);
39          }
40      }
41  
42      public static InMemoryCachedLoader wrap(PageLoader wrapped) {
43          return new InMemoryCachedLoader(wrapped);
44      }
45  
46  }