Commits

Marcel Soute  committed 69e7489

Add EhCache

  • Participants
  • Parent commits 0750edb
  • Branches ehcache

Comments (0)

Files changed (8)

File server/api/src/main/java/org/walli/api/ProxyResource.java

             response = cachedResponse.getResponse();
         } else {
             final Response liveResponse = getResponse(request.getUrl(), request.getInformation());
-            cache.add(request, new ProxyResponse(System.currentTimeMillis() + 50000, liveResponse));
+            cache.add(request, new ProxyResponse(liveResponse));
             response = liveResponse;
         }
         return response;

File server/api/src/test/java/org/walli/api/ProxyResourceTest.java

 import com.google.inject.AbstractModule;
 import com.google.inject.Guice;
 import com.google.inject.Injector;
+import net.sf.ehcache.Ehcache;
 import org.apache.commons.io.IOUtils;
 import org.junit.Before;
 import org.junit.Test;
 import org.walli.cache.ProxyRequest;
 import org.walli.cache.ProxyResponse;
 import org.walli.cache.SourceCache;
-import org.walli.connector.*;
+import org.walli.connector.AnonymousAuthInformation;
+import org.walli.connector.Connector;
+import org.walli.connector.OAuthHmacInformation;
 import org.walli.domain.Authentication;
 import org.walli.domain.Source;
 import org.walli.service.ISourceService;
 import javax.inject.Inject;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
-
 import java.lang.reflect.Field;
-import java.util.Hashtable;
 
 import static junit.framework.Assert.assertEquals;
 import static org.mockito.Matchers.eq;
         when(source.getPrivateKey()).thenReturn(IOUtils.toString(ProxyResourceTest.class.getResourceAsStream("/myrsakey.pk8")));
         when(source.getConsumerKey()).thenReturn(CONSUMER_KEY);
         when(source.getOauthToken()).thenReturn(OAUTH_TOKEN);
+
+        proxyCache.clear();
     }
 
 //    @Test
     @Test
     public void shouldNotCallConnectorWhenRequestIsCachedAndIsntExpired() throws Exception {
         final ProxyRequest<OAuthHmacInformation> proxyRequest = new ProxyRequest<OAuthHmacInformation>(URL + "/" + QUERY, new OAuthHmacInformation("", "", "", ""));
-        final ProxyResponse proxyResponse = new ProxyResponse(System.currentTimeMillis() + 10000, Response.ok().build());
+        final ProxyResponse proxyResponse = new ProxyResponse(Response.ok().build());
         proxyCache.add(proxyRequest, proxyResponse);
 
         when(source.getAuthentication()).thenReturn(Authentication.hmac);
 
     @Test
     public void shouldClearTheCache() throws Exception {
+
         final ProxyRequest<OAuthHmacInformation> proxyRequest = new ProxyRequest<OAuthHmacInformation>(URL + "/" + QUERY, new OAuthHmacInformation("", "", "", ""));
-        final ProxyResponse proxyResponse = new ProxyResponse(System.currentTimeMillis() + 10000, Response.ok().build());
+        final ProxyResponse proxyResponse = new ProxyResponse(Response.ok().build());
+
         proxyCache.add(proxyRequest, proxyResponse);
 
-        assertEquals(1, getCacheField().size());
+        assertEquals(1, getCacheField().getSize());
 
         resource.clear();
 
-        assertEquals(0, getCacheField().size());
+        assertEquals(0, getCacheField().getSize());
 
     }
 
      * @return cache The cache field.
      * @throws NoSuchFieldException
      */
-    private Hashtable<ProxyRequest, ProxyResponse> getCacheField() throws NoSuchFieldException, IllegalAccessException {
+    private Ehcache getCacheField() throws NoSuchFieldException, IllegalAccessException {
         Field field = proxyCache.getClass().getDeclaredField("cache");
         field.setAccessible(true);
-        return (Hashtable)field.get(proxyCache);
+        return (Ehcache)field.get(proxyCache);
     }
 }

File server/connector/pom.xml

             <groupId>rome</groupId>
             <artifactId>rome</artifactId>
         </dependency>
+
+        <!-- Caching -->
+        <dependency>
+            <groupId>net.sf.ehcache</groupId>
+            <artifactId>ehcache-core</artifactId>
+        </dependency>
     </dependencies>
 </project>

File server/connector/src/main/java/org/walli/cache/ProxyCache.java

 package org.walli.cache;
 
+import net.sf.ehcache.Cache;
+import net.sf.ehcache.CacheManager;
+import net.sf.ehcache.Element;
+
 import javax.inject.Singleton;
-import java.util.Hashtable;
 
 /**
  * ProxyCache is a caching provider that returns non-expired proxy responses that match given the proxy requests
 @Singleton
 public final class ProxyCache {
 
-    /** Holds all sources. */
-    private Hashtable<ProxyRequest, ProxyResponse> cache = new Hashtable<ProxyRequest, ProxyResponse>();
+    private static final String PROXY_REQUEST_CACHE = "ProxyRequest";
+
+    private final Cache cache;
+
+    public ProxyCache() {
+        System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
+        CacheManager manager = CacheManager.create();
+        if (!manager.cacheExists(PROXY_REQUEST_CACHE)) {
+            Cache memoryOnlyCache = new Cache(PROXY_REQUEST_CACHE, 5000, false, false, 300, 300);
+            manager.addCache(memoryOnlyCache);
+        }
+        cache = manager.getCache("ProxyRequest");
+    }
+
+    private final Cache cache;
+
+    public ProxyCache() {
+        System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
+        CacheManager manager = CacheManager.create();
+        if (!manager.cacheExists(PROXY_REQUEST_CACHE)) {
+            Cache memoryOnlyCache = new Cache(PROXY_REQUEST_CACHE, 5000, false, false, 300, 300);
+            manager.addCache(memoryOnlyCache);
+        }
+        cache = manager.getCache("ProxyRequest");
+    }
 
     /** Clear the cache. */
     public void clear() {
-        cache.clear();
+        cache.removeAll();
     }
 
+
     /**
      * Get the cached response for the given request.
      * Only responses that are still valid are returned.
      * @return response The response.
      */
     public ProxyResponse getCachedResponse(final ProxyRequest request) {
-        final ProxyResponse response = cache.get(request);
-        if (response != null && !response.isValid()) {
-            cache.remove(request);
+
+        if (cache.isKeyInCache(request.hashCode())) {
+            return (ProxyResponse) cache.get(request.hashCode()).getObjectValue();
+        } else {
             return null;
         }
-        return response;
     }
 
     /**
      * @param response The response.
      */
     public void add(final ProxyRequest request, final ProxyResponse response) {
-        cache.put(request, response);
+        cache.put(new Element(request.hashCode(), response));
     }
 }

File server/connector/src/main/java/org/walli/cache/ProxyResponse.java

 
 /** ProxyResponse is used for caching a response object for a specific period. */
 public class ProxyResponse {
-    private long validUntil;
     private Response response;
 
     /**
      * Constructor.
-     * @param validUntil Timestamp that indicate till when the response is valid.
      * @param response   The response.
      */
-    public ProxyResponse(long validUntil, Response response) {
-        this.validUntil = validUntil;
+    public ProxyResponse(Response response) {
         this.response = response;
     }
 
     public Response getResponse() {
         return response;
     }
-
-    /**
-     * Indicates if teh given response is still valid.
-     * @return <code>true</code> if valid, else <code>false</code>.
-     */
-    public boolean isValid() {
-        return System.currentTimeMillis() < validUntil;
-    }
 }

File server/connector/src/test/java/org/walli/cache/ProxyCacheTest.java

 import com.google.inject.AbstractModule;
 import com.google.inject.Guice;
 import com.google.inject.Injector;
+import net.sf.ehcache.Ehcache;
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 
 import javax.inject.Inject;
 import java.lang.reflect.Field;
-import java.util.Hashtable;
 
 import static junit.framework.Assert.assertEquals;
 import static junit.framework.Assert.assertNull;
-import static org.mockito.Mockito.when;
 
 /** Test class for {@link ProxyCache}. */
 @RunWith(MockitoJUnitRunner.class)
             }
         });
         injector.injectMembers(this);
+        cache.clear();
     }
 
     @Test
     }
 
     @Test
-    public void shouldReturnNullIfCachedInstanceIsExpired() throws Exception {
-        cache.add(request, response);
-        when(response.isValid()).thenReturn(false);
-        assertNull(cache.getCachedResponse(request));
-    }
-
-    @Test
     public void shouldAddToCache() throws Exception {
         cache.add(request, response);
-        assertEquals(getCacheField().size(), 1);
+
+        assertEquals(getCacheField().getSize(), 1);
     }
 
     @Test
     public void shouldNotAddTheTwice() throws Exception {
         cache.add(request, response);
         cache.add(request, response);
-        assertEquals(getCacheField().size(), 1);
+        assertEquals(getCacheField().getSize(), 1);
     }
 
     @Test
     public void shouldClearCache() throws Exception {
         cache.add(request, response);
-        assertEquals(getCacheField().size(), 1);
+        assertEquals(getCacheField().getSize(), 1);
         cache.clear();
-        assertEquals(getCacheField().size(), 0);
-    }
-
-    @Test
-    public void shouldRemoveResponseFromCacheIfExpired() throws Exception {
-        cache.add(request, response);
-        assertEquals(getCacheField().size(), 1);
-        when(response.isValid()).thenReturn(false);
-
-        cache.getCachedResponse(request);
-
-        assertEquals(getCacheField().size(), 0);
+        assertEquals(getCacheField().getSize(), 0);
     }
 
     /**
      * @return cache The cache field.
      * @throws NoSuchFieldException
      */
-    private Hashtable<ProxyRequest, ProxyResponse> getCacheField() throws NoSuchFieldException, IllegalAccessException {
+    private Ehcache getCacheField() throws NoSuchFieldException, IllegalAccessException {
         Field field = cache.getClass().getDeclaredField("cache");
         field.setAccessible(true);
-        return (Hashtable)field.get(cache);
+        return (Ehcache)field.get(cache);
     }
 }

File server/connector/src/test/java/org/walli/cache/ProxyResponseTest.java

 import javax.ws.rs.core.Response;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
 
 /** Test class for {@link ProxyResponse}. */
 @RunWith(MockitoJUnitRunner.class)
 
     @Test
     public void shouldSetValues() throws Exception {
-        assertTrue(new ProxyResponse(System.currentTimeMillis() + 10000, response).isValid());
-        assertFalse(new ProxyResponse(System.currentTimeMillis() - 10000, response).isValid());
-        assertEquals(response, new ProxyResponse(System.currentTimeMillis(), response).getResponse());
+        assertEquals(response, new ProxyResponse(response).getResponse());
     }
 }

File server/pom.xml

                 <version>${rome.version}</version>
             </dependency>
 
+            <!-- Caching -->
+
+            <dependency>
+                <groupId>net.sf.ehcache</groupId>
+                <artifactId>ehcache-core</artifactId>
+                <version>2.6.6</version>
+            </dependency>
+
             <!-- Testing -->
             <dependency>
                 <groupId>junit</groupId>