Package org.togglz.appengine.repository

Source Code of org.togglz.appengine.repository.MemcacheStateRepository

package org.togglz.appengine.repository;

import org.togglz.core.Feature;
import org.togglz.core.repository.FeatureState;
import org.togglz.core.repository.StateRepository;

import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

/**
* Decorates a given StateRepository adding caching capabilities. Leverages GAE's MemcacheServices. Default expiration time is
* 3600 seconds.
*
* @author Fábio Franco Uechi
*/
public class MemcacheStateRepository implements StateRepository {

    private StateRepository delegate;
    private MemcacheService cache = MemcacheServiceFactory.getMemcacheService();
    private Expiration expiration = Expiration.byDeltaSeconds(3600);
    private static final String KEY_PREFIX = MemcacheStateRepository.class.getName();

    public MemcacheStateRepository(StateRepository delegate) {
        this.delegate = delegate;
    }

    public MemcacheStateRepository(StateRepository delegate, int ttlInSeconds) {
        this(delegate);
        this.expiration = Expiration.byDeltaMillis(ttlInSeconds);
    }

    @Override
    public FeatureState getFeatureState(Feature feature) {
        FeatureState state = (FeatureState) cache.get(key(feature.name()));
        if (state == null) {
            state = delegate.getFeatureState(feature);
            cache.put(key(feature.name()), state, getExpiration());
        }
        return state;
    }

    String key(String featureName) {
        return KEY_PREFIX + featureName;
    }

    private Expiration getExpiration() {
        return this.expiration;
    }

    @Override
    public void setFeatureState(FeatureState featureState) {
        delegate.setFeatureState(featureState);
        cache.delete(key(featureState.getFeature().name()));
    }
}
TOP

Related Classes of org.togglz.appengine.repository.MemcacheStateRepository

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.