Package de.peacei.gae.foodsupplier.data

Source Code of de.peacei.gae.foodsupplier.data.WeekplanCache

/**
*
*/
package de.peacei.gae.foodsupplier.data;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;
import com.google.inject.Inject;

import de.peacei.gae.foodsupplier.out.RenderingService;

/**
* @author peacei
*
*/
public class WeekplanCache {
 
  private Cache cache = null;
 
  @Inject
  private RenderingService renderingService;
 
  @SuppressWarnings("unchecked")
  public WeekplanCache() {
   
    @SuppressWarnings("rawtypes")
    Map props = new HashMap();
        props.put(GCacheFactory.EXPIRATION_DELTA, 604800);
   
        try {
            CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
            cache = cacheFactory.createCache(Collections.emptyMap());
        } catch (CacheException e) {  }
  }
 
  public void put(String format, Weekplan weekplan) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    renderingService.renderWeekplan(weekplan, os, format);
   
    String cacheKey = format +':' + weekplan.getMensa().getId() + '@'
        + String.valueOf(weekplan.getWeek())
        + '.' + String.valueOf(weekplan.getYear());
   
    String cacheValue = null;
    try {
      cacheValue = new String(os.toByteArray(), "UTF8");
    } catch(UnsupportedEncodingException ex) { }
   
    cache.put(cacheKey, cacheValue);
  }
 
 
  public String get(String format, String mensaId, int week, int year) {
    String cacheKey = format + ':' + mensaId + '@' + String.valueOf(week)
        + '.' + String.valueOf(year);

    if(cache.containsKey(cacheKey)) return (String) cache.get(cacheKey);
    else return null;
  }
 
 
  public void removeFromCache(String format, String mensaId, int week, int year) {
    String cacheKey = format + ':' + mensaId + '@' + String.valueOf(week)
        + '.' + String.valueOf(year);
   
    if(cache!=null && cache.containsKey(cacheKey)) {
      cache.remove(cacheKey);
    }
  }
 
  public void clear() {
    cache.clear();
  }
}
TOP

Related Classes of de.peacei.gae.foodsupplier.data.WeekplanCache

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.