001 /**
002 * Copyright (C) 2009-2011 the original author or authors.
003 * See the notice.md file distributed with this work for additional
004 * information regarding copyright ownership.
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019 package org.fusesource.restygwt.client.cache;
020
021 import java.util.ArrayList;
022 import java.util.List;
023 import java.util.logging.Logger;
024
025 import com.google.gwt.http.client.Response;
026 import com.google.gwt.logging.client.LogConfiguration;
027 import com.google.gwt.user.client.Timer;
028
029 public class VolatileQueueableCacheStorage extends DefaultQueueableCacheStorage {
030
031 /**
032 * how long will a cachekey be allowed to exist
033 */
034 private static final int DEFAULT_LIFETIME_MS = 30 * 1000;
035
036 private final int lifetimeMillis;
037
038 public VolatileQueueableCacheStorage(){
039 this(DEFAULT_LIFETIME_MS);
040 }
041 public VolatileQueueableCacheStorage(int lifetimeMillis){
042 this.lifetimeMillis = lifetimeMillis;
043 }
044
045 private final List<Timer> timers = new ArrayList<Timer>();
046
047 protected void putResult(final CacheKey key, final Response response, final String scope) {
048 final Timer t = new Timer() {
049 public void run() {
050 try {
051 if (LogConfiguration.loggingIsEnabled()) {
052 Logger.getLogger(VolatileQueueableCacheStorage.class.getName())
053 .finer("removing cache-key " + key + " from scope \"" + scope + "\"");
054 }
055 cache.get(scope).remove(key);
056 timers.remove(this);
057 } catch (Exception ex) {
058 Logger.getLogger(VolatileQueueableCacheStorage.class.getName())
059 .severe(ex.getMessage());
060 }
061 }
062 };
063 t.schedule(lifetimeMillis);
064 timers.add(t);
065
066 super.putResult(key, response, scope);
067 }
068
069 @Override
070 public void purge() {
071 super.purge();
072 if (LogConfiguration.loggingIsEnabled()) {
073 Logger.getLogger(DefaultQueueableCacheStorage.class.getName()).finer("remove "
074 + timers.size() + " timers from list.");
075 }
076 for (Timer t: timers) {
077 t.cancel();
078 }
079 timers.clear();
080 }
081
082 }