001/* 002 * (C) Copyright 2010-13 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Olivier Grisel 016 * 017 */ 018package org.nuxeo.ecm.platform.suggestbox.jsf; 019 020import java.io.Serializable; 021 022/** 023 * Simple cached item holder with time + key invalidation strategy 024 */ 025public class Cached<T> implements Serializable { 026 027 private static final long serialVersionUID = 1L; 028 029 public long cachedAt; 030 031 public long expireMillis; 032 033 public Object[] keys = new Object[0]; 034 035 public T value; 036 037 public boolean expired = false; 038 039 public Cached(long expireMillis) { 040 this.expireMillis = expireMillis; 041 // expired by default 042 expired = true; 043 } 044 045 public void cache(T value, Object... keys) { 046 this.expired = false; 047 this.cachedAt = System.currentTimeMillis(); 048 this.keys = keys; 049 this.value = value; 050 } 051 052 public void expire() { 053 expired = true; 054 value = null; 055 keys = new Object[0]; 056 } 057 058 public boolean hasExpired(Object... invalidationKeys) { 059 if (expired) { 060 return true; 061 } 062 long now = System.currentTimeMillis(); 063 if (now - cachedAt > expireMillis) { 064 return true; 065 } 066 if (invalidationKeys.length != keys.length) { 067 return true; 068 } 069 for (int i = 0; i < keys.length; i++) { 070 if (!keys[i].equals(invalidationKeys[i])) { 071 return true; 072 } 073 } 074 return false; 075 } 076 077 /** 078 * Empty marker to be used as default value 079 */ 080 public static <E> Cached<E> expired(long expireMillis) { 081 return new Cached<E>(expireMillis); 082 } 083}