Saturday, June 28, 2014

An Apex Cookie Wrapper

Cookies are a means of storing data in the browser during a user's Salesforce session. Common uses include tracking a session ID, storing breadcrumbs and user preferences, and 'remembering' some aspects of the state of visited pages - such as sort order, pagination details, etc. The data is stored by the browser, which sends the cookie back to Salesforce on each page load.

Salesforce provides a very useful System.Cookie class, but I found myself wanting something a bit simpler. Below is a class you can use to easily create and manage your cookies.

SF_Cookie

/**
 * A wrapper class for System.Cookie. Provides helper methods for creating,
 * removing, getting the value, and checking the existence of a cookie.
 * <p>
 * Usage:
 * <p>store your cookie definition as a static class variable:
 * <code>private static SF_Cookie myCookie = new SF_Cookie('my cookie', null, 600, false);</code>
 * <p>create a cookie if it doesn't exist:
 * <code>if (!myCookie.exists()) myCookie.create('my value');</code>
 * <p>remove a cookie
 * <code>myCookie.remove();</code>
 */
public class SF_Cookie {
  //-------------------------------------------------------------------------
  // Constants
  public final static String  DEFAULT_PATH      = '/';
  public final static Integer DEFAULT_MAX_AGE   = -1;
  public final static Boolean DEFAULT_IS_SECURE = false;
  
  
  //-------------------------------------------------------------------------
  // Properties
  @testVisible private System.Cookie theCookie;
  
  @testVisible private String name;
  @testVisible private String path;
  @testVisible private Integer maxAge;
  @testVisible private Boolean isSecure;
  
  
  //-------------------------------------------------------------------------
  // Methods
  /**
   * constructs a cookie object, but doesn't 'set' it
   * @param name may not be null
   * @param path
   * @param maxAge defaults to -1 (session); may not be 0 (indicates delete)
   * @param isSecure defaults to false
   * @see System.Cookie
   */
  public SF_Cookie(String name, String path, Integer maxAge, Boolean isSecure) {
    SF.preCondition((null != name) && ('' != name.trim()), 'SF_Cookie: name is required');
    SF.preCondition(0 != maxAge, 'SF_Cookie: maxAge of 0 indicates delete. Use the remove method instead.');
    
    this.name = name;
    this.path = path;
    this.maxAge = maxAge;
    this.isSecure = isSecure;
  }
  
  /** removes any existing cookie, then creates a new one */
  public void create(String value) {
    SF.preCondition((null != value) && ('' != value.trim()), 'Cookie.create: value is required');
    
    this.remove();
    theCookie = new System.Cookie(name, value, path, maxAge, isSecure);
    ApexPages.currentPage().setCookies(new System.Cookie[] { theCookie });
  }
  
  /** returns true if the cookie exists and is accessible to the current page */
  public Boolean exists() {
    theCookie = ApexPages.currentPage().getCookies().get(name);
    return (null != theCookie);
  }
    
  /** returns the value of the cookie */
  public String getValue() {
    SF.preCondition(this.exists(), 'Cookie.getValue: cookie must exist');
      
    return ApexPages.currentPage().getCookies().get(name).getValue();
  }
    
  /** removes the cookie */
  public void remove() {
    ApexPages.currentPage().setCookies(new System.Cookie[] { new System.Cookie(name, null, null, 0, false) });
    ApexPages.currentPage().getCookies().put(name, null);
    theCookie = null;
  }
}

No comments:

Post a Comment