/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.jetspeed.services.portletcache;

import javax.servlet.ServletConfig;

// Jetspeed
import org.apache.jetspeed.portal.portlets.AbstractPortlet;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.jetspeed.services.portletcache.Cacheable;

// Turbine
import org.apache.turbine.util.Log;
import org.apache.turbine.services.TurbineBaseService;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.cache.CachedObject;
import org.apache.turbine.services.cache.Refreshable;
import org.apache.turbine.services.cache.RefreshableCachedObject;
import org.apache.turbine.services.cache.ObjectExpiredException;


/**
 * <P>This implementation of the PortletCache service is a simple adapter to
 * the Turbine GlobalCacheService</p>
 *
 * @author <a href="mailto:burton@apache.org">Kevin A. Burton</a>
 * @author <a href="mailto:raphael@apache.org">Raphaël Luta</a>
 * @author <a href="mailto:paulsp@apache.org">Paul Spencer</a>
 * @version $Id: JetspeedPortletCacheService.java,v 1.7 2002/02/05 03:08:05 paulsp Exp $
 */
public class JetspeedPortletCacheService
extends TurbineBaseService
implements PortletCacheService {
    
    private static int DefaultTimeToLiveMillis = (JetspeedResources.getInt(TurbineServices.SERVICE_PREFIX
    + PortletCacheService.SERVICE_NAME
    + ".TimeToLive.default", (30 * 60 * 1000))); // 30 minutes
    
    /**
     * Called during Turbine.init()
     *
     * @param config A ServletConfig.
     */
    public void init( ServletConfig config ) {
        try {
            Log.info( "JetspeedPortletCacheService early init()....starting!");
            if (DefaultTimeToLiveMillis < 0) {
                Log.info( "JetspeedPortletCacheService - By default refreshable objects will live for ever");
            } else {
                Log.info( "JetspeedPortletCacheService - By default refreshable objects will be removed after " 
                + DefaultTimeToLiveMillis + " Millis ( " 
                + (DefaultTimeToLiveMillis/(1000*60)) + " minutes " 
                + ((DefaultTimeToLiveMillis%(1000*60))/1000.00) 
                + " Seconds "+")" );
            }
            // no specific init required, relies on GlobalCacheService
            Log.info( "JetspeedPortletCacheService early init()....finished!");
        }
        catch (Exception e) {
            Log.error( "Cannot initialize JetspeedPortletCacheService!" );
            Log.error(e);
        }
        setInit(true);
    }
    
    /**
     * Add a Cacheable object to the cache.
     *
     * @param item the object to store in the Cache
     */
    public void addCacheable( Cacheable item ) {
        
        String handle = item.getHandle();
        
        if ( handle.length() == 0 ) {
            throw new RuntimeException("You must specify a handle for the item you want to cache.");
        }
        
        if ( item.isCacheable() ) {
            CachedObject cachedObject = null;
            Long expirationMillis = item.getExpirationMillis();
            if (expirationMillis != null) {
                if (System.currentTimeMillis() < expirationMillis.longValue()) {
                    cachedObject.setExpires(expirationMillis.longValue() - cachedObject.getCreated());
                }
            }
            if (item instanceof Refreshable) {
                RefreshableCachedObject rco = new RefreshableCachedObject( (Refreshable) item);
                if (item instanceof AbstractPortlet) {
                    AbstractPortlet portlet = (AbstractPortlet)item;
                    String tempString =  portlet.getPortletConfig().getInitParameter("_TimeToLive");
                    if (tempString != null) {
                        rco.setTTL(Integer.parseInt(tempString));
                    } else {
                        rco.setTTL(DefaultTimeToLiveMillis);
                    }
                } else {
                    rco.setTTL(DefaultTimeToLiveMillis);
                }
                cachedObject = rco;
                
            } else {
                cachedObject = new CachedObject(item);
            }
            item.setCachedObject(cachedObject);

            // Add object to cache
            GlobalCache.addObject( handle , cachedObject);
         }
    }
    
    /**
     * Removes an object from the cache based on its handle
     *
     * @see PortletCacheService#removeCacheable
     * @param handle the identifier of the object we wish to retrieve
     */
    public void removeCacheable( String handle ) {
        
        CachedObject obj = null;
        
        try {
            obj = GlobalCache.getObject( handle );
        } catch ( ObjectExpiredException e) {
            // nothing to do if already expired
        }
        
        if ( obj != null ) {
            obj.setStale(true);
        }
    }
    
    /**
     * Retrieves a Cacheable object from the cache.
     *
     * @param handle the identifier of the object we wish to retrieve
     * @return the cacehd object or null if not found
     */
    public Cacheable getCacheable( String handle ) {
        
        CachedObject obj = null;
        
        try {
            obj = GlobalCache.getObject( handle );
        } catch (ObjectExpiredException e) {
            Log.info( "cache miss, object expired: " + handle );
        }
        
        if ( obj == null ) {
            //Log.info( "cache miss: " + handle );
            return null;
        } /*else {
            Log.info( "cache hit: " + handle );
            } */
        
        return (Cacheable)obj.getContents();
        
    }
    
}

