001/*
002 * (C) Copyright 2010-2013 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *    Olivier Grisel
018 *
019 */
020package org.nuxeo.ecm.platform.suggestbox.jsf;
021
022import java.io.Serializable;
023
024/**
025 * Simple cached item holder with time + key invalidation strategy
026 */
027public class Cached<T> implements Serializable {
028
029    private static final long serialVersionUID = 1L;
030
031    public long cachedAt;
032
033    public long expireMillis;
034
035    public Object[] keys = new Object[0];
036
037    public T value;
038
039    public boolean expired = false;
040
041    public Cached(long expireMillis) {
042        this.expireMillis = expireMillis;
043        // expired by default
044        expired = true;
045    }
046
047    public void cache(T value, Object... keys) {
048        this.expired = false;
049        this.cachedAt = System.currentTimeMillis();
050        this.keys = keys;
051        this.value = value;
052    }
053
054    public void expire() {
055        expired = true;
056        value = null;
057        keys = new Object[0];
058    }
059
060    public boolean hasExpired(Object... invalidationKeys) {
061        if (expired) {
062            return true;
063        }
064        long now = System.currentTimeMillis();
065        if (now - cachedAt > expireMillis) {
066            return true;
067        }
068        if (invalidationKeys.length != keys.length) {
069            return true;
070        }
071        for (int i = 0; i < keys.length; i++) {
072            if (!keys[i].equals(invalidationKeys[i])) {
073                return true;
074            }
075        }
076        return false;
077    }
078
079    /**
080     * Empty marker to be used as default value
081     */
082    public static <E> Cached<E> expired(long expireMillis) {
083        return new Cached<E>(expireMillis);
084    }
085}