ghoward 2003/07/13 19:50:46
Added: src/blocks/eventcache/java/org/apache/cocoon/acting
CacheEventAction.java
src/blocks/eventcache/java/org/apache/cocoon/caching/impl
DefaultEventRegistryImpl.java
EventRegistryDataWrapper.java
EventAwareCacheImpl.java
src/blocks/eventcache/java/org/apache/cocoon/caching/validity
EventValidity.java Event.java NameValueEvent.java
NamedEvent.java
src/blocks/eventcache/conf eventcache.xconf
eventcache.xsamples eventregistry.xconf
src/blocks/eventcache/lib .cvsignore
src/blocks/eventcache/samples event.js sitemap.xmap
eventcache.xsp
src/blocks/eventcache/java/org/apache/cocoon/generation
EventCachedFileGenerator.java
src/blocks/eventcache/java/org/apache/cocoon/caching
EventRegistry.java EventAware.java
Log:
refactor event cache, move from scratchpad to block,
add sample demonstrating the new type of validity,
and uncaching from flow (FOM) and action.
TODO: thread safety
Revision Changes Path
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/acting/CacheEventAction.java
Index: CacheEventAction.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.acting;
import java.util.Map;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.caching.Cache;
import org.apache.cocoon.caching.impl.EventAwareCacheImpl;
import org.apache.cocoon.caching.validity.NamedEvent;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Redirector;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
/**
* Very experimental start at external cache invalidation.
* Warning - API very unstable. Do not use!
*
* Simple action to cause notification of a NamedEvent to an EventAwareCacheImpl.
* The event name is taken from a sitemap parameter named "event".
*
* This action returns null (fails) if the configured event is null or the
* empty string. Otherwise, it succeeds and returns an empty Map.
*
* This is used in the Event based cache example.
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version CVS $Id: CacheEventAction.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public class CacheEventAction extends ComposerAction implements ThreadSafe {
/**
* Lookup the cache and call its processEvent method. Returns an
* empty map to signal success.
*/
public Map act(Redirector redirector,
SourceResolver resolver,
Map objectModel,
String src,
Parameters par
) throws Exception {
Cache cache = (Cache)this.manager.lookup(Cache.ROLE);
if (cache instanceof EventAwareCacheImpl) {
Request request = ObjectModelHelper.getRequest(objectModel);
String eventName = par.getParameter("event");
if (getLogger().isDebugEnabled()) {
getLogger().debug("Configured for cache event named: " + eventName);
}
if (eventName == null || "".equals(eventName)) {
return null;
}
((EventAwareCacheImpl)cache).processEvent(
new NamedEvent(eventName));
}
this.manager.release(cache);
return EMPTY_MAP;
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/impl/DefaultEventRegistryImpl.java
Index: DefaultEventRegistryImpl.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.caching.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.context.Context;
import org.apache.avalon.framework.context.ContextException;
import org.apache.avalon.framework.context.Contextualizable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.Constants;
import org.apache.cocoon.caching.EventRegistry;
import org.apache.cocoon.caching.PipelineCacheKey;
import org.apache.cocoon.caching.validity.Event;
import org.apache.commons.collections.MultiHashMap;
/**
* This implementation of <code>EventRegistry</code> stores the event-key
* mappings in a simple pair of <code>MultiMap</code>s. It handles
* persistence by serializing an <code>EventRegistryDataWrapper</code> to
* disk.
*
* @since 2.1
* @author <a href="mailto:[EMAIL PROTECTED]">Geoff Howard</a>
* @version CVS $Id: DefaultEventRegistryImpl.java,v 1.1 2003/07/14 02:50:45 ghoward
Exp $
*/
public class DefaultEventRegistryImpl
extends AbstractLogEnabled
implements EventRegistry,
ThreadSafe,
Disposable,
Contextualizable {
private File m_persistentFile;
private static final String PERSISTENT_FILE = "ev_cache.ser";
private File m_workDir;
private MultiHashMap m_keyMMap;
private MultiHashMap m_eventMMap;
/**
* Registers (stores) a two-way mapping between this Event and this
* PipelineCacheKey for later retrieval.
*
* @param event The event to
* @param key
*/
public void register(Event e, PipelineCacheKey key) {
m_keyMMap.put(key,e);
m_eventMMap.put(e,key);
}
/**
* Retrieve all pipeline keys mapped to this event.
*/
public PipelineCacheKey[] keysForEvent(Event e) {
Collection coll = (Collection)m_eventMMap.get(e);
if (coll==null || coll.isEmpty()) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("The event map returned empty");
}
return null;
} else {
return (PipelineCacheKey[])coll.toArray(new
PipelineCacheKey[coll.size()]);
}
}
/**
* When a CachedResponse is removed from the Cache, any entries
* in the event mapping must be cleaned up.
*/
public void removeKey(PipelineCacheKey key) {
Collection coll = (Collection)m_keyMMap.get(key);
if (coll==null || coll.isEmpty()) {
return;
} else {
// get the iterator over all matching PCK keyed
// entries in the key-indexed MMap.
Iterator it = coll.iterator();
while (it.hasNext()) {
/* remove all entries in the event-indexed map where this
* PCK key is the value.
*/
Object o = it.next();
if (o != null) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Removing from event mapping: " +
o.toString());
}
m_eventMMap.remove((Event)o,key);
}
}
}
// remove all entries in the key-indexed map where this PCK key
// is the key -- confused yet?
m_keyMMap.remove(key);
}
/**
* Return the keys held as an array
*/
public PipelineCacheKey[] allKeys() {
Set keys = this.m_keyMMap.keySet();
return (PipelineCacheKey[])keys.toArray(
new PipelineCacheKey[keys.size()]);
}
/**
* Remove all registered data.
*/
public void clear() {
m_keyMMap.clear();
m_eventMMap.clear();
}
/**
* We must persist the data at container shutdown. If the serialization
* fails, an error is logged but not thrown. The missing/invalid state is
* handled at startup.
*/
public void dispose() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(
new
FileOutputStream(this.m_persistentFile));
EventRegistryDataWrapper ecdw = new EventRegistryDataWrapper();
ecdw.setupMaps(this.m_keyMMap, this.m_eventMMap);
oos.writeObject(ecdw);
oos.flush();
} catch (FileNotFoundException e) {
getLogger().error("Unable to persist EventRegistry", e);
} catch (IOException e) {
getLogger().error("Unable to persist EventRegistry", e);
} finally {
try {
if (oos != null) oos.close();
} catch (IOException e) {}
}
m_keyMMap.clear();
m_keyMMap = null;
m_eventMMap.clear();
m_eventMMap = null;
}
/**
* Set up the persistence file.
*/
public void contextualize(Context context) throws ContextException {
org.apache.cocoon.environment.Context ctx =
(org.apache.cocoon.environment.Context) context.get(
Constants.CONTEXT_ENVIRONMENT_CONTEXT);
// set up file
m_persistentFile = new File(
ctx.getRealPath("/WEB-INF"),
DefaultEventRegistryImpl.PERSISTENT_FILE);
if (m_persistentFile == null) {
throw new ContextException("Could not obtain persistent file. " +
"The cache event registry cannot be " +
"used inside an unexpanded WAR file.");
}
}
/**
* Recover state by de-serializing the data wrapper. If this fails
* a new empty mapping is initialized and the Cache is signalled of
* the failure so it can clean up.
*
* @return true if de-serializing was successful, false otherwise.
*/
public boolean init() {
return recover();
}
private boolean recover() {
if (this.m_persistentFile.exists()) {
ObjectInputStream ois = null;
EventRegistryDataWrapper ecdw = null;
try {
ois = new ObjectInputStream(
new FileInputStream(this.m_persistentFile));
ecdw = (EventRegistryDataWrapper)ois.readObject();
} catch (FileNotFoundException e) {
getLogger().error("Unable to retrieve EventRegistry", e);
createBlankCache();
return false;
} catch (IOException e) {
getLogger().error("Unable to retrieve EventRegistry", e);
createBlankCache();
return false;
} catch (ClassNotFoundException e) {
getLogger().error("Unable to retrieve EventRegistry", e);
createBlankCache();
return false;
} finally {
try {
if (ois != null) ois.close();
} catch (IOException e) {
// ignore
}
}
this.m_eventMMap = ecdw.get_eventMap();
this.m_keyMMap = ecdw.get_keyMap();
} else {
getLogger().warn(this.m_persistentFile + " does not exist - Unable to " +
"retrieve EventRegistry.");
createBlankCache();
return false;
}
return true;
}
// TODO: don't hardcode initial size
private void createBlankCache() {
this.m_eventMMap = new MultiHashMap(100);
this.m_keyMMap = new MultiHashMap(100);
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/impl/EventRegistryDataWrapper.java
Index: EventRegistryDataWrapper.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.caching.impl;
import java.io.Serializable;
import org.apache.commons.collections.MultiHashMap;
/**
* A light object for persisting the state of an EventRegistry implementation
* based on two MultiHashMaps.
*
* @author [EMAIL PROTECTED]
* @version CVS $Id: EventRegistryDataWrapper.java,v 1.1 2003/07/14 02:50:45 ghoward
Exp $
*/
public class EventRegistryDataWrapper implements Serializable {
private MultiHashMap m_keyMMap;
private MultiHashMap m_eventMMap;
public EventRegistryDataWrapper() {
this.m_keyMMap = null;
this.m_eventMMap = null;
}
public void setupMaps(MultiHashMap keyMap, MultiHashMap eventMap) {
this.m_keyMMap = keyMap;
this.m_eventMMap = eventMap;
}
public MultiHashMap get_eventMap() {
return m_eventMMap;
}
public MultiHashMap get_keyMap() {
return m_keyMMap;
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/impl/EventAwareCacheImpl.java
Index: EventAwareCacheImpl.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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.
*/
package org.apache.cocoon.caching.impl;
import java.util.Iterator;
import java.util.Map;
import org.apache.avalon.framework.activity.Initializable;
import org.apache.avalon.framework.component.ComponentException;
import org.apache.avalon.framework.component.ComponentManager;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.caching.CachedResponse;
import org.apache.cocoon.caching.EventAware;
import org.apache.cocoon.caching.EventRegistry;
import org.apache.cocoon.caching.PipelineCacheKey;
import org.apache.cocoon.caching.validity.Event;
import org.apache.cocoon.caching.validity.EventValidity;
import org.apache.excalibur.source.SourceValidity;
import org.apache.excalibur.source.impl.validity.AggregatedValidity;
/**
* Very experimental start at external cache invalidation.
* Warning - API very unstable. Do not use!
* (But it's getting closer!)
*
* This implementation holds all mappings between Events and PipelineCacheKeys
* in two MultiHashMap to facilitate efficient lookup by either as Key.
*
* TODO: Test performance.
* TODO: Handle MultiThreading
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version $Id: EventAwareCacheImpl.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public class EventAwareCacheImpl
extends CacheImpl
implements Initializable, EventAware {
private ComponentManager m_manager;
private EventRegistry m_eventRegistry;
/**
* Clears the entire Cache, including all registered event-pipeline key
* mappings..
*/
public void clear() {
super.clear();
m_eventRegistry.clear();
}
/**
* When a new Pipeline key is stored, it needs to be have its
* <code>SourceValidity</code> objects examined. For every
* <code>EventValidity</code> found, its <code>Event</code> will be
* registered with this key in the <code>EventRegistry</code>.
*
* <code>AggregatedValidity</code> is handled recursively.
*/
public void store(Map objectModel,
PipelineCacheKey key,
CachedResponse response)
throws ProcessingException {
SourceValidity[] validities = response.getValidityObjects();
for (int i=0; i< validities.length;i++) {
SourceValidity val = validities[i];
examineValidity(val, key);
}
super.store(objectModel, key, response);
}
/**
* Look up the EventRegistry
*/
public void compose(ComponentManager manager) throws ComponentException {
this.m_manager = manager;
super.compose(manager);
this.m_eventRegistry = (EventRegistry)manager.lookup(EventRegistry.ROLE);
}
/**
* Un-register this key in the EventRegistry in addition to
* removing it from the Store
*/
public void remove(PipelineCacheKey key) {
super.remove(key);
m_eventRegistry.removeKey(key);
}
/**
* Receive notification about the occurrence of an Event.
* If this event has registered pipeline keys, remove them
* from the Store and unregister them
* @param e The Event to be processed.
*/
public void processEvent(Event e) {
PipelineCacheKey[] pcks = m_eventRegistry.keysForEvent(e);
for (int i=0;i<pcks.length; i++) {
if (pcks[i] != null) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Processing cache event, found Pipeline key: "
+ pcks[i].toString());
}
/* every pck associated with this event needs to be
* removed -- regardless of event mapping. and every
* event mapped to those keys needs to be removed
* recursively.
*/
remove(pcks[i]);
}
}
}
/**
* Get the EventRegistry ready, and make sure it does not contain
* orphaned Event/PipelineKey mappings.
*/
public void initialize() throws Exception {
if (!m_eventRegistry.init()) {
// Is this OK in initialize? I think it depends
// on the Store(s) being initialized first.
super.clear();
} else {
// Not sure if we want this overhead here, but where else?
veryifyEventCache();
}
}
/**
* Ensure that all PipelineCacheKeys registered to events still
* point to valid cache entries. Having an isTotallyEmpty() on
* Store might make this less necessary, as the most likely time
* to discover orphaned entries is at startup. This is because
* stray events could hang around indefinitely if the cache is
* removed abnormally or is not configured with persistence.
*/
public void veryifyEventCache() {
PipelineCacheKey[] pcks = m_eventRegistry.allKeys();
for (int i=0; i<pcks.length; i++) {
if (!this.containsKey(pcks[i])) {
m_eventRegistry.removeKey(pcks[i]);
if (getLogger().isDebugEnabled()) {
getLogger().debug("Cache key no longer valid: " +
pcks[i]);
}
}
}
}
/**
* Release resources
*/
public void dispose() {
m_manager.release(m_eventRegistry);
super.dispose();
m_manager = null;
m_eventRegistry = null;
}
private void examineValidity(SourceValidity val, PipelineCacheKey key) {
if (val instanceof AggregatedValidity) {
handleAggregatedValidity((AggregatedValidity)val, key);
} else if (val instanceof EventValidity) {
handleEventValidity((EventValidity)val, key);
}
}
private void handleAggregatedValidity(
AggregatedValidity val,
PipelineCacheKey key) {
// AggregatedValidity must be investigated further.
Iterator it = val.getValidities().iterator();
while (it.hasNext()) {
SourceValidity thisVal = (SourceValidity)it.next();
// Allow recursion
examineValidity(thisVal, key);
}
}
private void handleEventValidity(EventValidity val, PipelineCacheKey key) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Found EventValidity: " + val.toString());
}
m_eventRegistry.register(val.getEvent(),key);
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/validity/EventValidity.java
Index: EventValidity.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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.
*/
package org.apache.cocoon.caching.validity;
import org.apache.excalibur.source.SourceValidity;
/**
* Very experimental start at external cache invalidation.
* Warning - API very unstable. Do not use! In fact, if this
* becomes useful, it would probably move to Excalibur SourceResolve.
*
* The SourceValidity object for cache invalidation based on
* external events.
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version $Id: EventValidity.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public class EventValidity implements SourceValidity {
private Event m_event;
/**
* Constructor requires any subclass of Event.
* @param ev
*/
public EventValidity(Event ev) {
m_event = ev;
}
/**
* Returns the specific Event this validity is based on.
*
* @return Event
*/
public Event getEvent() {
return m_event;
}
/**
* Basic implementation is always valid until event signals
* otherwise. May never need other behavior.
*/
public int isValid() {
return VALID;
}
/**
* Older style of isValid
*/
public int isValid(SourceValidity sv) {
if (sv instanceof EventValidity) {
return VALID;
}
return INVALID;
}
public boolean equals(Object o) {
if (o instanceof EventValidity) {
return m_event.equals(((EventValidity)o).getEvent());
}
return false;
}
public int hashCode() {
return m_event.hashCode();
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/validity/Event.java
Index: Event.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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.
*/
package org.apache.cocoon.caching.validity;
import java.io.Serializable;
/**
* Very experimental start at external cache invalidation.
* Warning - API very unstable. Do not use! In fact, if this
* becomes useful, it would probably move to Excalibur SourceResolve.
*
* Base class encapsulating the information about an external
* uncache event.
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version $Id: Event.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public abstract class Event implements Serializable {
/**
* Used by EventValidity for equals(Object o) which
* is important for determining whether a received event
* should uncache a held Pipeline key.
*
* @param event Another Event to compare.
* @return true if
*/
public abstract boolean equals(Event e);
/**
* This hash code is the only way the system can locate
* matching Events when a new event notification is received.
*/
public abstract int hashCode();
public boolean equals(Object o) {
if (o instanceof Event) {
return equals((Event)o);
}
return false;
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/validity/NameValueEvent.java
Index: NameValueEvent.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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.
*/
package org.apache.cocoon.caching.validity;
/**
* Very experimental start at external cache invalidation.
* Warning - API very unstable. Do not use! In fact, if this
* becomes useful, it would probably move to Excalibur SourceResolve.
*
* An external uncache event that consists of a name/value pair.
* An example might be "table_name", "primary_key"
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version $Id: NameValueEvent.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public class NameValueEvent extends Event {
private String m_name;
private String m_value;
private int m_hashcode;
/**
* Constructor requires two Strings - the name/value
* pair which defines this Event.
*
* @param name
* @param value
*/
public NameValueEvent(String name, String value) {
m_name = name;
m_value = value;
m_hashcode = (name + value).hashCode();
}
/**
* Must return true when both name and value are
* equivalent Strings.
*/
public boolean equals(Event e) {
if (e instanceof NameValueEvent) {
NameValueEvent nve = (NameValueEvent)e;
return ( m_name.equals(nve.m_name) &&
m_value.equals(nve.m_value) );
}
return false;
}
public int hashCode() {
return m_hashcode;
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/validity/NamedEvent.java
Index: NamedEvent.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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.
*/
package org.apache.cocoon.caching.validity;
/**
* Very experimental start at external cache invalidation.
* Warning - API very unstable. Do not use! In fact, if this
* becomes useful, it would probably move to Excalibur SourceResolve.
*
* An External cache event that consists of just a name. Examples
* (not necessarily useful) could include "Easter" or "Shutdown"
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version $Id: NamedEvent.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public class NamedEvent extends Event {
private String m_name;
private int m_hashcode;
/**
* Constructor takes a simple String as event name.
*
* @param String name
*/
public NamedEvent(String name) {
m_name = name;
m_hashcode = name.hashCode();
}
/**
* Every NamedEvent where the name string is equal must
* return true.
*/
public boolean equals(Event e) {
if (e instanceof NamedEvent) {
return m_name.equals(((NamedEvent)e).m_name);
}
return false;
}
public int hashCode() {
return m_hashcode;
}
}
1.1 cocoon-2.1/src/blocks/eventcache/conf/eventcache.xconf
Index: eventcache.xconf
===================================================================
<?xml version="1.0"?>
<xconf xpath="/cocoon" unless="[EMAIL
PROTECTED]'org.apache.cocoon.caching.impl.EventAwareCacheImpl']">
<!-- Override default Cache impl and use the event aware version -->
<component role="org.apache.cocoon.caching.Cache"
class="org.apache.cocoon.caching.impl.EventAwareCacheImpl"/>
</xconf>
1.1 cocoon-2.1/src/blocks/eventcache/conf/eventcache.xsamples
Index: eventcache.xsamples
===================================================================
<?xml version="1.0"?>
<xsamples xpath="/samples" unless="[EMAIL PROTECTED]'Event Based Cache']">
<group name="Event Based Cache">
<sample name="Event Based Cache" href="eventcache/demo?pageKey=one">
A sample demonstrating a new system of cache invalidation based on
events usually external to Cocoon. Example uses include cache content
until a back-end database is updated, or EJB signals an update.
</sample>
</group>
</xsamples>
1.1 cocoon-2.1/src/blocks/eventcache/conf/eventregistry.xconf
Index: eventregistry.xconf
===================================================================
<?xml version="1.0"?>
<xconf xpath="/cocoon"
unless="[EMAIL
PROTECTED]'org.apache.cocoon.caching.impl.DefaultEventRegistryImpl']">
<!-- The event registry which maps Cache events to Pipeline keys -->
<component role="org.apache.cocoon.caching.EventRegistry"
class="org.apache.cocoon.caching.impl.DefaultEventRegistryImpl"/>
</xconf>
1.1 cocoon-2.1/src/blocks/eventcache/lib/.cvsignore
<<Binary file>>
1.1 cocoon-2.1/src/blocks/eventcache/samples/event.js
Index: event.js
===================================================================
var role = Packages.org.apache.cocoon.caching.Cache.ROLE;
function cacheEvent() {
var cache = cocoon.getComponent(role);
var event = new Packages.org.apache.cocoon.caching.validity.NamedEvent("one");
var rand = Math.random() * 10000000000000000000;
cache.processEvent(event);
cocoon.releaseComponent(cache);
cocoon.redirectTo("demo?pageKey=" + cocoon.request.pageKey + "&rand="+rand);
}
1.1 cocoon-2.1/src/blocks/eventcache/samples/sitemap.xmap
Index: sitemap.xmap
===================================================================
<?xml version="1.0"?>
<!--
CVS $Id$
Event Cache Sample
-->
<map:sitemap xmlns:map="http://apache.org/cocoon/sitemap/1.0">
<map:components>
<map:generators default="file"/>
<map:transformers default="xslt"/>
<map:readers default="resource"/>
<map:serializers default="html"/>
<map:matchers default="wildcard"/>
<map:selectors default="browser"/>
<map:actions>
<map:action name="cacheevent" src="org.apache.cocoon.acting.CacheEventAction"/>
</map:actions>
</map:components>
<map:flow language="javascript">
<map:script src="event.js"/>
</map:flow>
<map:views>
<map:view from-label="content" name="content">
<map:serialize type="xml"/>
</map:view>
</map:views>
<map:pipelines>
<map:pipeline>
<map:match pattern="flow">
<map:call function="cacheEvent"/>
</map:match>
<map:match pattern="action">
<map:act type="cacheevent">
<map:parameter name="event" value="{request-param:event}"/>
</map:act>
<map:redirect-to
uri="demo?pageKey={request-param:pageKey}&rand={random:x}"/>
</map:match>
<map:match pattern="*">
<map:generate type="serverpages" src="eventcache.xsp"/>
<map:transform src="context://samples/stylesheets/dynamic-page2html.xsl">
<map:parameter name="servletPath" value="{request:servletPath}"/>
<map:parameter name="sitemapURI" value="{request:sitemapURI}"/>
<map:parameter name="contextPath" value="{request:contextPath}"/>
<map:parameter name="file" value="eventcache.xsp"/>
<map:parameter name="remove" value="{0}"/>
</map:transform>
<map:serialize/>
</map:match>
</map:pipeline>
</map:pipelines>
</map:sitemap>
1.1 cocoon-2.1/src/blocks/eventcache/samples/eventcache.xsp
Index: eventcache.xsp
===================================================================
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
XSP event-based cache sample.
$Id$
-->
<xsp:page language="java"
xmlns:xsp="http://apache.org/xsp"
xmlns:xsp-request="http://apache.org/xsp/request/2.0">
<xsp:structure>
<xsp:include>org.apache.excalibur.source.SourceValidity</xsp:include>
<xsp:include>org.apache.cocoon.caching.validity.EventValidity</xsp:include>
<xsp:include>org.apache.cocoon.caching.validity.NamedEvent</xsp:include>
<xsp:include>java.io.Serializable</xsp:include>
</xsp:structure>
<xsp:logic>
// artificial slowdown to make the effects of the cache visible
final int DELAY_SECS = 2;
/**
* Generate the unique key for the cache.
*
* This key must be unique inside the space of this XSP page, it is used
* to find the page contents in the cache (if getValidity says that the
* contents are still valid).
*
* This method will be invoked before the getValidity() method.
*
* @return The generated key or null if the component
* is currently not cacheable.
*/
public Serializable getKey()
{
// for our test, pages having the same value of "pageKey" will share
// the same cache location
String key = request.getParameter("pageKey") ;
return ((key==null||"".equals(key)) ? "one" : key);
}
/**
* Generate the validity object, tells the cache how long to
* keep contents having this key around. In this case, it will
* be until an Event is retrieved matching the NamedEvent created below.
*
* Before this method can be invoked the getKey() method
* will be invoked.
*
* @return The generated validity object or null if the
* component is currently not cacheable.
*/
public SourceValidity getValidity() {
String key = request.getParameter("pageKey") ;
return new EventValidity(
new NamedEvent(
(key==null||"".equals(key)) ? "one" : key));
}
</xsp:logic>
<page>
<title>Demonstrating Event-Aware Caching</title>
<content>
<para>
This xsp page is based on (copied from) the cacheable xsp sample
but there are some important differences. If you don't already
understand at least the basics of caching in Cocoon, you should
probably start there, not here. Read the text below, and the
sitemap and source for more details.
</para>
<para>
I pause for <xsp:expr>DELAY_SECS</xsp:expr> seconds during generation,
so
that you can tell if I'm being served from the cache or not.
<br/>
What you see here was generated on <b><xsp:expr>new
java.util.Date()</xsp:expr></b>.
</para>
<para>
I'm cached for each unique value of request parameter 'pageKey'. Other
parameters do not matter.
<br/>
Here the value is:
<b><xsp-request:get-parameter name="pageKey"/></b>.
<br/>
If this is not the same as the 'pageKey' parameter in the page URL, we
have a problem.
</para>
<para>
Unlike other cacheable pages in Cocoon, I can be un-cached by
events external
to Cocoon - for instance, when a database table or row is
updated.
<br/>
My cache entry will be invalidated (actually, removed) when an
event named
<i><xsp-request:get-parameter name="pageKey"/></i> occurs.
This can be manually
simulated by clicking one of the "uncache" links below.
</para>
<para>Test links:
<ul>
<li><a target="_new" href="?pageKey=one">pageKey=one</a>
(<a href="action?pageKey=one&event=one">uncache with
action</a>)
(<a href="flow?pageKey=one&event=one">uncache with
flow</a>)</li>
<li><a target="_new" href="?pageKey=two">pageKey=two</a>
(<a href="action?pageKey=two&event=two">uncache with
action</a>)
(<a href="flow?pageKey=two&event=two">uncache with
flow</a>)</li>
</ul>
Note: the random numbers you see included in the url after an uncache
link
serve two purposes in the example, making it easier to see the effect of
the
cache invalidation. They prevent browser caching and they demonstrate
that
only our designated key matters in the retrieval from cache.
</para>
<para>
This event based cache system consists essentially of three
parts:
<ul>
<li>A new type of SourceValidity, EventValidity, which
contains information
on the Event which will invalidate this cached
content. Until this event is
received, EventValidities will usually always return
valid, though they don't
have to.</li>
<li>An extension to Cocoon's Cache implementation.
Cocoon's Cache is really just
a thin wrapper around Avalon-Excalibur's Store
project. The EventAwareCacheImpl
does two things. It examines each pipeline on its way
into the cache to
determine if any of its SourceValidities are instances
of EventValidity. If so,
it notifies an event registry as described next. The
second critical function of
the EventAware cache implementation is that it allows
other components to
contact it and notify it of an Event. The Cache then
looks up the keys
mapped to that event in the event registry and cleans
out the cache and
registry accordingly.</li>
<li>The EventRegistry is responsible for mapping
Events to cache keys, and
providing information about that mapping to systems
that need it, usually just
the EventAwareCache. Another crucial responsibility
of the EventRegistry is to
persist its data across container shutdown and
startup. The default implementation
does by serializing an object to disk (currently in
WEB-INF). If recovering this
fails, the EventAwareCache is notified, and it is
expected to ensure there are no
orphaned EventValidities (currently by clearing the
entire cache).
</li>
</ul>
Note that though this example uses xsp with actions or flow,
any pipeline component can be
made to use EventValidity, and any code with access to the
ComponentManager can
translate real-world events to Events and notify the Cache of
them.
</para>
<xsp:logic>
// slowdown page generation.
try {
Thread.sleep(DELAY_SECS * 1000L);
} catch (InterruptedException ie) {
// Not much that can be done...
}
</xsp:logic>
</content>
</page>
</xsp:page>
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/generation/EventCachedFileGenerator.java
Index: EventCachedFileGenerator.java
===================================================================
/*
* Created on Jun 28, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.apache.cocoon.generation;
import org.apache.cocoon.caching.validity.EventValidity;
import org.apache.cocoon.caching.validity.NamedEvent;
import org.apache.excalibur.source.SourceValidity;
/**
* @author ghoward
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class EventCachedFileGenerator extends FileGenerator {
private EventValidity validity = null;
/* (non-Javadoc)
* @see org.apache.cocoon.caching.CacheableProcessingComponent#getValidity()
*/
public SourceValidity getValidity() {
if (validity == null) {
validity = new EventValidity(new NamedEvent("test"));
}
return validity;
}
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/EventRegistry.java
Index: EventRegistry.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.caching;
import org.apache.avalon.framework.component.Component;
import org.apache.cocoon.caching.validity.Event;
/**
* The <code>EventRegistry</code> is responsible for the two-way many-to-many
* mapping between cache <code>Event</code>s and
* <code>PipelineCacheKey</code>s necessary to allow for efficient
* event-based cache invalidation.
*
* @since 2.1
* @author <a href="mailto:[EMAIL PROTECTED]">Geoff Howard</a>
* @version CVS $Id: EventRegistry.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public interface EventRegistry extends Component {
/**
* The Avalon ROLE for this component
*/
String ROLE = EventRegistry.class.getName();
/**
* Map an event to a key
*
* @param event
* @param key
*/
public void register(Event e, PipelineCacheKey key);
/**
* Remove all occurances of the specified key from the registry.
*
* @param key - The key to remove.
*/
public void removeKey(PipelineCacheKey key);
/**
* Retrieve an array of all keys mapped to this event.
*
* @param event
* @return an array of keys which should not be modified or null if
* no keys are mapped to this event.
*/
public PipelineCacheKey[] keysForEvent(Event e);
/**
* Retrieve an array of all keys regardless of event mapping, or null if
* no keys are registered..
*
* @return an array of keys which should not be modified
*/
public PipelineCacheKey[] allKeys();
/**
* Clear all event-key mappings from the registry.
*/
public void clear();
/**
* Request that the registry get ready for normal operation. Depending
* on the implementation, the component may need this opportunity to
* retrieve persisted data.
*
* If recovering persisted data was not successful, the component must
* signal that the Cache may contain orphaned EventValidity objects by
* returning false. The Cache should then ensure that all pipelines
* associated with EventValidities are either removed or re-associated
* (if possible).
*
* @return true if the Component recovered its state successfully,
* false otherwise.
*/
public boolean init();
}
1.1
cocoon-2.1/src/blocks/eventcache/java/org/apache/cocoon/caching/EventAware.java
Index: EventAware.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, 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 Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", 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 (INCLU-
DING, 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 and was originally created by
Stefano Mazzocchi <[EMAIL PROTECTED]>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.caching;
import org.apache.cocoon.caching.validity.Event;
/**
* Defines the simple contract for components that need to receive notification
* of cache Events.
*
* @author Geoff Howard ([EMAIL PROTECTED])
* @version CVS $Id: EventAware.java,v 1.1 2003/07/14 02:50:45 ghoward Exp $
*/
public interface EventAware {
/**
* Receive notification of an Event.
*
* @param The Event
*/
public void processEvent(Event e);
}