Package com.google.appengine.api.memcache

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


            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 = System.currentTimeMillis();
            while (System.currentTimeMillis() - started < MAX_UIDL_WAIT_MILLISECONDS) {
                locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
                        MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
                if (locked || ServletPortletHelper.isUIDLRequest(request)) {
                    /*
                     * Done if we got a lock. Will also avoid retrying if
                     * there's a UIDL request because those are retried from the
                     * client without keeping the server thread stalled.
                     */
                    break;
                }
                try {
                    Thread.sleep(RETRY_AFTER_MILLISECONDS);
                } catch (InterruptedException e) {
                    getLogger().finer(
                            "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
            VaadinSession 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
                    + (getMaxInactiveIntervalSeconds(session) * 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) {
            getLogger().log(Level.WARNING, "DeadlineExceeded for {0}",
                    session.getId());
            sendDeadlineExceededNotification(request, response);
        } catch (NotSerializableException e) {
            getLogger().log(Level.SEVERE, "Not serializable!", e);

            // TODO this notification is usually not shown - should we redirect
            // in some other way - can we?
            sendNotSerializableNotification(request, response);
        } catch (Exception e) {
            getLogger().log(Level.WARNING,
                    "An exception occurred while servicing request.", e);

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


   * Storage key for the unique instance.
   */
  public static final String UNIQUE_INSTANCE_KEY = "SPADGER_CONFIG";

  public static SpadgerConfig getInstance() {
    MemcacheService cache = MemcacheServiceFactory.getMemcacheService();

    // Checks if the config object is cached in memory.
    SpadgerConfig config = (SpadgerConfig) cache
        .get(SpadgerConfig.UNIQUE_INSTANCE_KEY);

    // if the config object is not in memory, go to the data to load it, and
    // then store it in the memory
    if (config == null) {
      LOGGER
          .debug("Unabled to obtain SpadgerConfig instance from cache, trying the datastore instead");

      PersistenceManager pm = PMF.get().getPersistenceManager();
      try {
        config = pm.getObjectById(SpadgerConfig.class,
            SpadgerConfig.UNIQUE_INSTANCE_KEY);

        LOGGER.debug("Placing the SpadgerConfig instance into memcache");

        cache.put(SpadgerConfig.UNIQUE_INSTANCE_KEY, config);
      } catch (JDOObjectNotFoundException e) {
        LOGGER
            .debug("SpadgerConfig instance not found, creating one instead...");

        config = new SpadgerConfig();
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

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

public class MySecondTest extends LocalCacheTestBase2GAE{
    // run this test twice to prove we're not leaking any state across tests
    private void doTest() {
        MemcacheService ms = MemcacheServiceFactory.getMemcacheService();
        assertFalse(ms.contains("yar"));
        ms.put("yar", "foo");
        assertTrue(ms.contains("yar"));
    }
View Full Code Here

        String logoutUrl = userService.createLogoutURL("/");

        Entity userPrefs = null;
        if (user != null) {
            DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
            MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();

            String cacheKey = "UserPrefs:" + user.getUserId();
            userPrefs = (Entity) memcache.get(cacheKey);
            if (userPrefs == null) {
                log.warning("CACHE MISS");

                Key userKey = KeyFactory.createKey("UserPrefs", user.getUserId());
                try {
                    userPrefs = ds.get(userKey);
                    memcache.put(cacheKey, userPrefs);
                } catch (EntityNotFoundException e) {
                    // No user preferences stored.
                }
            } else {
                log.warning("CACHE HIT");
View Full Code Here

        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        Key userKey = KeyFactory.createKey("UserPrefs", user.getUserId());
        Entity userPrefs = new Entity(userKey);

        MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
        String cacheKey = "UserPrefs:" + user.getUserId();

        try {
            int tzOffset = new Integer(req.getParameter("tz_offset")).intValue();

            userPrefs.setProperty("tz_offset", tzOffset);
            userPrefs.setProperty("user", user);
            ds.put(userPrefs);
            memcache.delete(cacheKey);

        } catch (NumberFormatException nfe) {
            // User entered a value that wasn't an integer. Ignore for now.
        }
View Full Code Here

  public static Map<String, Long> storeMultipleCounters(Map<String, Long> allCounters, String namespace, long initalValue) {
    if (null == allCounters || allCounters.isEmpty()) {
      return new HashMap<String, Long>();
    }
   
    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(namespace);
   
    return memcacheService.incrementAll(allCounters, initalValue);
  }
View Full Code Here

  public static Map<String, Object> getMultipleCounters(Collection<String> allCounterNames, String namespace) {
    if (null == allCounterNames || allCounterNames.isEmpty()) {
      return new HashMap<String, Object>();
    }
   
    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(namespace);
   
    return memcacheService.getAll(allCounterNames);
  }
View Full Code Here

    Set<String> prefixedCounters = new HashSet<String>();
    for (String name : counterNames) {
      prefixedCounters.add(slotPrefix + "_" + name); //change each counters name to the slotPrefix_countername
    }

    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(namespace);
   
    return memcacheService.getAll(prefixedCounters);
  }
View Full Code Here

    if (null == counterNames || counterNames.isEmpty()) {
      return;
    }
   
    _logger.info("Deleting counter keys (count: " + counterNames.size() + ")");
    MemcacheService memcacheService = MemcacheServiceFactory.getMemcacheService(namespace);
   
    memcacheService.deleteAll(counterNames);
  }
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.