Package com.google.appengine.api.memcache

Examples of com.google.appengine.api.memcache.MemcacheService


      LOGGER.severe(StackTraceUtil.getStackTrace(e));
      cacheName = "default";
    }
   
    //InternalCache internalCache = this.getCache(cacheName);
    MemcacheService syncCache = this.getCache(cacheName);
    syncCache.clearAll();
    /*if(internalCache == null) {
      LOGGER.log(Level.INFO, "NO CACHE TO FLUSH! with name -> " + cacheName);
    } else {
      LOGGER.log(Level.INFO, "Flushing cache with name -> " + cacheName);
      this.addCache(cacheName, null);
View Full Code Here


  protected MemcacheService getCache(String name) {
    InternalCache cache = null;
    String oldNameSpace = NamespaceManager.get() != null ? NamespaceManager.get() : "";
    String namespace = !"".equals(oldNameSpace)? oldNameSpace + "." + name : name;
    LOGGER.info("(getCache)Cache namespace: " + namespace);
    MemcacheService syncCache = null;
    try {
      syncCache = MemcacheServiceFactory.getMemcacheService(namespace);
    } catch(Exception e) {
      LOGGER.severe("Error getting cache with namespace: " + namespace);
      LOGGER.severe(StackTraceUtil.getStackTrace(e));
View Full Code Here

  }
 
  private HashMap<String, Object> getDataFromCache(Long courseId, Locale locale) throws Exception {
    HashMap<Long, HashMap<String, Object>> courses = null;
    HashMap<String, Object> courseData = null;
    MemcacheService syncCache = null;
    boolean cached = false;
   
    try {
      syncCache = MemcacheServiceFactory.getMemcacheService("test-"+locale.getLanguage());
    } catch(Exception e) {
      LOGGER.severe("Error getting cache for towns by name map: ");
      LOGGER.severe(StackTraceUtil.getStackTrace(e));
    }
   
    try {
      courses = (HashMap<Long, HashMap<String, Object>>)syncCache.get("coursesData");
    } catch(InvalidValueException e) {
      LOGGER.severe(StackTraceUtil.getStackTrace(e));
    }
   
    if(courses == null) {
      courses = new HashMap<Long, HashMap<String, Object>>();
    }
   
    courseData = courses.get(courseId);
    if(courseData == null) {
      courseData = new HashMap<String, Object>();
      Course course = this.serviceLocator.getCourseService().getCourse(courseId, locale);
      School school = this.serviceLocator.getSchoolService().getSchool(course.getSchool(), locale);
      Provider provider = this.serviceLocator.getProviderService().getProviderById(school.getProvider(), locale);
     
      String townName = school.getContactInfo() != null &&
          school.getContactInfo().getCity() != null ?
          school.getContactInfo().getCity() : "";
     

      //Town town = this.getTownByName(townName, locale);

      Town town = this.serviceLocator.getTerritorialService().getTownsMap(locale).get(townName);
     
      Province province = new Province();
      Region region = new Region();
     
      if(town != null && town.getId() != null) {
        region = this.serviceLocator.getTerritorialService().getRegionsMap(locale).get(town.getRegion());
        province = this.serviceLocator.getTerritorialService().getProvincesMap(locale).get(town.getProvince());
      } else {
        town = new Town();
      }
     
     
      // Metadata
      StringBuffer keyWords = new StringBuffer();
      for(Category tag : course.getTags()) {
        keyWords.append(tag.getCategory()).append(",");
      }
     
      // Create courseData
      courseData.put("provider", provider);
      courseData.put("school", school);
      courseData.put("course", course);
      courseData.put("province", province);
      courseData.put("region", region);
      courseData.put("town", town);
      courseData.put("tags", keyWords.toString());
     
      courses.put(courseId, courseData);
     
      //Store in cache
      syncCache.put("coursesData", courses);
     
    } else {
      LOGGER.log(Level.INFO, "CourseData from cache!!!!!!!");
    }
   
View Full Code Here

            cleanSession(request);
            return;
        }

        boolean locked = false;
        MemcacheService memcache = null;
        String mutex = MUTEX_BASE + session.getId();
        memcache = MemcacheServiceFactory.getMemcacheService();
        try {
            // try to get lock
            long started = new Date().getTime();
            // non-UIDL requests will try indefinitely
            while (requestType != RequestType.UIDL
                    || new Date().getTime() - started < MAX_UIDL_WAIT_MILLISECONDS) {
                locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
                        MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
                if (locked) {
                    break;
                }
                try {
                    Thread.sleep(RETRY_AFTER_MILLISECONDS);
                } catch (InterruptedException e) {
                    log
                            .info("Thread.sleep() interrupted while waiting for lock. Trying again. "
                                    + e);
                }
            }

            if (!locked) {
                // Not locked; only UIDL can get trough here unlocked: tell
                // client to retry
                response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                // Note: currently interpreting Retry-After as ms, not sec
                response
                        .setHeader("Retry-After", "" + RETRY_AFTER_MILLISECONDS);
                return;
            }

            // de-serialize or create application context, store in session
            ApplicationContext ctx = getApplicationContext(request, memcache);

            super.service(request, response);

            // serialize
            started = new Date().getTime();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(ctx);
            oos.flush();
            byte[] bytes = baos.toByteArray();

            started = new Date().getTime();

            String id = AC_BASE + session.getId();
            Date expire = new Date(started
                    + (session.getMaxInactiveInterval() * 1000));
            Expiration expires = Expiration.onDate(expire);

            memcache.put(id, bytes, expires);

            DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
            Entity entity = new Entity(AC_BASE, id);
            entity.setProperty(PROPERTY_EXPIRES, expire.getTime());
            entity.setProperty(PROPERTY_DATA, new Blob(bytes));
            ds.put(entity);

        } catch (DeadlineExceededException e) {
            log.severe("DeadlineExceeded for " + session.getId());
            sendDeadlineExceededNotification(request, response);
        } catch (NotSerializableException e) {
            // TODO this notification is usually not shown - should we redirect
            // in some other way - can we?
            sendNotSerializableNotification(request, response);
            log.severe("NotSerializableException: " + getStackTraceAsString(e));
        } catch (Exception e) {
            sendCriticalErrorNotification(request, response);
            log.severe(e + ": " + getStackTraceAsString(e));
        } finally {
            // "Next, please!"
            if (locked) {
                memcache.delete(mutex);
            }
            cleanSession(request);
        }
    }
View Full Code Here

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

public class MemcacheManager implements CacheManager {
  public <K, V> Cache<K, V> getCache(String name) throws CacheException {
    MemcacheService memcacheService = MemcacheServiceFactory
        .getMemcacheService(name);

    return new Memcache<K, V>(memcacheService);
  }
View Full Code Here

  }
 
  private HashMap<String, Object> getDataFromCache(Long courseId, Locale locale) throws Exception {
    HashMap<Long, HashMap<String, Object>> courses = null;
    HashMap<String, Object> courseData = null;
    MemcacheService syncCache = null;
    boolean cached = false;
   
    try {
      syncCache = MemcacheServiceFactory.getMemcacheService("test-"+locale.getLanguage());
    } catch(Exception e) {
      LOGGER.severe("Error getting cache for towns by name map: ");
      LOGGER.severe(StackTraceUtil.getStackTrace(e));
    }
   
    try {
            courses = (HashMap<Long, HashMap<String, Object>>)syncCache.get("coursesData");
      } catch(InvalidValueException e) {
             LOGGER.severe(StackTraceUtil.getStackTrace(e));
      }
   
    if(courses == null) {
      courses = new HashMap<Long, HashMap<String, Object>>();
    }
   
    courseData = courses.get(courseId);
    if(courseData == null) {
      courseData = new HashMap<String, Object>();
      Course course = this.serviceLocator.getCourseService().getCourse(courseId, locale);
      School school = this.serviceLocator.getSchoolService().getSchool(course.getSchool(), locale);
      Provider provider = this.serviceLocator.getProviderService().getProviderById(school.getProvider(), locale);
     
      String townName = school.getContactInfo() != null &&
          school.getContactInfo().getCity() != null ?
          school.getContactInfo().getCity() : "";
     

      //Town town = this.getTownByName(townName, locale);

      Town town = this.serviceLocator.getTerritorialService().getTownsMap(locale).get(townName);
     
      Province province = new Province();
      Region region = new Region();
     
      if(town != null && town.getId() != null) {
        region = this.serviceLocator.getTerritorialService().getRegionsMap(locale).get(town.getRegion());
        province = this.serviceLocator.getTerritorialService().getProvincesMap(locale).get(town.getProvince());
      } else {
        town = new Town();
      }
     
     
      // Metadata
      StringBuffer keyWords = new StringBuffer();
      for(Category tag : course.getTags()) {
        keyWords.append(tag.getCategory()).append(",");
      }
     
      // Create courseData
      courseData.put("provider", provider);
      courseData.put("school", school);
      courseData.put("course", course);
      courseData.put("province", province);
      courseData.put("region", region);
      courseData.put("town", town);
      courseData.put("tags", keyWords.toString());
     
      courses.put(courseId, courseData);
     
      //Store in cache
      syncCache.put("coursesData", courses);
     
    } else {
      LOGGER.log(Level.INFO, "CourseData from cache!!!!!!!");
    }
   
View Full Code Here

            cleanSession(request);
            return;
        }

        boolean locked = false;
        MemcacheService memcache = null;
        String mutex = MUTEX_BASE + session.getId();
        memcache = MemcacheServiceFactory.getMemcacheService();
        try {
            // try to get lock
            long started = new Date().getTime();
            // non-UIDL requests will try indefinitely
            while (requestType != RequestType.UIDL
                    || new Date().getTime() - started < MAX_UIDL_WAIT_MILLISECONDS) {
                locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
                        MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
                if (locked) {
                    break;
                }
                try {
                    Thread.sleep(RETRY_AFTER_MILLISECONDS);
                } catch (InterruptedException e) {
                    log
                            .info("Thread.sleep() interrupted while waiting for lock. Trying again. "
                                    + e);
                }
            }

            if (!locked) {
                // Not locked; only UIDL can get trough here unlocked: tell
                // client to retry
                response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                // Note: currently interpreting Retry-After as ms, not sec
                response
                        .setHeader("Retry-After", "" + RETRY_AFTER_MILLISECONDS);
                return;
            }

            // de-serialize or create application context, store in session
            ApplicationContext ctx = getApplicationContext(request, memcache);

            super.service(request, response);

            // serialize
            started = new Date().getTime();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(ctx);
            oos.flush();
            byte[] bytes = baos.toByteArray();

            started = new Date().getTime();

            String id = AC_BASE + session.getId();
            Date expire = new Date(started
                    + (session.getMaxInactiveInterval() * 1000));
            Expiration expires = Expiration.onDate(expire);

            memcache.put(id, bytes, expires);

            DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
            Entity entity = new Entity(AC_BASE, id);
            entity.setProperty(PROPERTY_EXPIRES, expire.getTime());
            entity.setProperty(PROPERTY_DATA, new Blob(bytes));
            ds.put(entity);

        } catch (DeadlineExceededException e) {
            log.severe("DeadlineExceeded for " + session.getId());
            sendDeadlineExceededNotification(request, response);
        } catch (NotSerializableException e) {
            log.severe("NotSerializableException: " + getStackTraceAsString(e));

            // TODO this notification is usually not shown - should we redirect
            // in some other way - can we?
            sendNotSerializableNotification(request, response);
        } catch (Exception e) {
            log.severe(e + ": " + getStackTraceAsString(e));

            sendCriticalErrorNotification(request, response);
        } finally {
            // "Next, please!"
            if (locked) {
                memcache.delete(mutex);
            }
            cleanSession(request);
        }
    }
View Full Code Here

    directory.register(MAPPING);
    assertEquals(OBJECT_ID, directory.cache.get(OBJECT_ID).getCached().getObjectId());
  }

  public void testSuccessfulLookup() throws Exception {
    MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
    WaveletDirectory directory = newDirectory(newDatastore(), memcache);

    directory.register(MAPPING);
    memcache.clearAll();
    assertNull(directory.cache.get(OBJECT_ID));
    assertEquals(OBJECT_ID, directory.lookup(OBJECT_ID).getObjectId());
    assertEquals(OBJECT_ID, directory.cache.get(OBJECT_ID).getCached().getObjectId());
  }
View Full Code Here

    assertEquals(null, directory.lookup(OBJECT_ID));
    assertEquals(null, directory.cache.get(OBJECT_ID).getCached());
  }

  public void testLookupUsesCache() throws Exception {
    MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
    WaveletDirectory directory = newDirectory(newDatastore(), memcache);

    directory.cache.put(OBJECT_ID, new WaveletDirectory.CacheEntry(MAPPING));
    assertEquals(OBJECT_ID, directory.lookup(OBJECT_ID).getObjectId());
    directory.cache.put(OBJECT_ID, new WaveletDirectory.CacheEntry(null));
View Full Code Here

        UserPrefs userPrefs = null;

        String cacheKey = getCacheKeyForUser(user);

        try {
            MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
            if (memcache.contains(cacheKey)) {
                logger.warning("CACHE HIT: " + cacheKey);
                userPrefs = (UserPrefs) memcache.get(cacheKey);
                return userPrefs;
            }
            logger.warning("CACHE MISS: " + cacheKey);
            // If the UserPrefs object isn't in memcache,
            // fall through to the datastore.
View Full Code Here

TOP

Related Classes of com.google.appengine.api.memcache.MemcacheService

Copyright © 2018 www.massapicom. 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.