alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Play Framework/Scala example source code file (Cache.java)

This example Play Framework source code file (Cache.java) is included in my "Source Code Warehouse" project. The intent of this project is to help you more easily find Play Framework (and Scala) source code examples by using tags.

All credit for the original source code belongs to Play Framework; I'm just trying to make examples easier to find. (For my Scala work, see my Scala examples and tutorials.)

Play Framework tags/keywords

cache, callable, exception, object, play, play framework, suppresswarnings, t

The Cache.java Play Framework example source code

/*
 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
 */
package play.cache;

import java.util.concurrent.Callable;

/**
 * Provides an access point for Play's cache service.
 */
public class Cache {

  /**
   * Retrieves an object by key.
   *
   * @return object
   */
  public static Object get(String key) {
      return play.libs.Scala.orNull(play.api.cache.Cache.get(key,play.api.Play.unsafeApplication()));
  }

  /**
   * Retrieve a value from the cache, or set it from a default Callable function.
   * 
   * @param key Item key.
   * @param block block returning value to set if key does not exist
   * @param expiration expiration period in seconds.
   * @return value 
   */
  @SuppressWarnings("unchecked")
  public static <T> T getOrElse(String key, Callable<T> block, int expiration) throws Exception{
     Object r = play.libs.Scala.orNull(play.api.cache.Cache.get(key,play.api.Play.unsafeApplication()));
     if (r == null) {
         T value = block.call();
         set(key,value,expiration);
         return value;
     } else return (T)r;
     
  }
  
  /**
   * Sets a value with expiration.
   * 
   * @param expiration expiration in seconds
   */
  public static void set(String key, Object value, int expiration) {
      play.api.cache.Cache.set(key,value,expiration, play.api.Play.unsafeApplication());
  }

  /**
   * Sets a value without expiration.
   *
   */
  public static void set(String key, Object value) {
      play.api.cache.Cache.set(key,value, 0, play.api.Play.unsafeApplication());
  }

  public static void remove(String key) {
      play.api.cache.Cache.remove(key, play.api.Play.unsafeApplication());
  }
}

Other Play Framework source code examples

Here is a short list of links related to this Play Framework Cache.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.