/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2002 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
apache@apache.org.
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 <stefano@apache.org>. For more information on the Apache
Software Foundation, please see <http://www.apache.org/>.
*/
package org.apache.cocoon.components.store;
import org.apache.avalon.framework.activity.Initializable;
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.AbstractLoggable;
import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameterizable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.avalon.framework.thread.ThreadSafe;
import org.apache.cocoon.Constants;
import org.apache.cocoon.util.IOUtils;
import com.coyotegulch.jisp.BTreeIndex;
import com.coyotegulch.jisp.IndexedObjectDatabase;
import com.coyotegulch.jisp.KeyNotFound;
import com.coyotegulch.jisp.KeyObject;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
/**
* This store is based on the Jisp library
* (http://www.coyotegulch.com/jisp/index.html). This store uses B-Tree indexes
* to access variable-length serialized data stored in files.
*
* @author <a href="mailto:g-froehlich@gmx.de">Gerhard Froehlich</a>
* @author <a href="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
* @version CVS $Id: JispFilesystemStore.java,v 1.2 2002/02/22 07:00:13 cziegeler Exp $
*/
public final class JispFilesystemStore
extends AbstractLoggable
implements Store, Contextualizable, ThreadSafe, Initializable, Parameterizable {
protected File workDir;
protected File cacheDir;
/**
* The directory repository
*/
protected File directoryFile;
protected volatile String directoryPath;
/**
* The database
*/
private File databaseFile;
private File indexFile;
private int mOrder;
private IndexedObjectDatabase mDatabase;
private BTreeIndex mIndex;
/**
* Sets the repository's location
*
* @param directory the new directory value
* @exception IOException
*/
public void setDirectory(final String directory)
throws IOException {
this.setDirectory(new File(directory));
}
/**
* Sets the repository's location
*
* @param directory the new directory value
* @exception IOException
*/
public void setDirectory(final File directory)
throws IOException {
this.directoryFile = directory;
/* Save directory path prefix */
this.directoryPath = IOUtils.getFullFilename(this.directoryFile);
this.directoryPath += File.separator;
if (!this.directoryFile.exists()) {
/* Create it new */
if (!this.directoryFile.mkdir()) {
throw new IOException("Error creating store directory '" +
this.directoryPath + "'");
}
}
/* Is given file actually a directory? */
if (!this.directoryFile.isDirectory()) {
throw new IOException("'" + this.directoryPath + "' is not a directory");
}
/* Is directory readable and writable? */
if (!(this.directoryFile.canRead() && this.directoryFile.canWrite())) {
throw new IOException("Directory '" + this.directoryPath +
"' is not readable/writable");
}
}
/**
* Contextualize the Component
*
* @param context the Context of the Application
* @exception ContextException
*/
public void contextualize(final Context context) throws ContextException {
this.workDir = (File)context.get(Constants.CONTEXT_WORK_DIR);
this.cacheDir = (File)context.get(Constants.CONTEXT_CACHE_DIR);
}
/**
* Configure the Component.<br>
* A few options can be used
* <UL>
* <LI> datafile = the name of the data file (Default: cocoon.dat)
* </LI>
* <LI> indexfile = the name of the index file (Default: cocoon.idx)
* </LI>
* <LI> order = The page size of the B-Tree</LI>
* </UL>
*
* @param params the configuration paramters
* @exception ParameterException
*/
public void parameterize(Parameters params) throws ParameterException {
try {
if (params.getParameterAsBoolean("use-cache-directory", false)) {
if (this.getLogger().isDebugEnabled())
getLogger().debug("Using cache directory: " + cacheDir);
setDirectory(cacheDir);
} else if (params.getParameterAsBoolean("use-work-directory", false)) {
if (this.getLogger().isDebugEnabled())
getLogger().debug("Using work directory: " + workDir);
setDirectory(workDir);
} else if (params.getParameter("directory", null) != null) {
String dir = params.getParameter("directory");
dir = IOUtils.getContextFilePath(workDir.getPath(), dir);
if (this.getLogger().isDebugEnabled())
getLogger().debug("Using directory: " + dir);
setDirectory(new File(dir));
} else {
try {
// Default
setDirectory(workDir);
} catch (IOException e) {
// Ignored
}
}
} catch (IOException e) {
throw new ParameterException("Unable to set directory", e);
}
String databaseName = params.getParameter("datafile", "cocoon.dat");
String indexName = params.getParameter("indexfile", "cocoon.idx");
mOrder = params.getParameterAsInteger("order", 301);
if (getLogger().isDebugEnabled()) {
this.getLogger().debug("Database file name = " + databaseName);
this.getLogger().debug("Index file name = " + indexName);
this.getLogger().debug("Order=" + mOrder);
}
databaseFile = new File(directoryFile, databaseName);
indexFile = new File(directoryFile, indexName);
}
/**
* Initialize the Component
*/
public void initialize() {
if (getLogger().isDebugEnabled()) {
getLogger().debug("initialize() JispFilesystemStore");
}
try {
if (databaseFile.exists()) {
if (getLogger().isDebugEnabled()) {
this.getLogger().debug("initialize(): Datafile exists");
}
mDatabase = new IndexedObjectDatabase(databaseFile.toString(), false);
mIndex = new BTreeIndex(indexFile.toString());
mDatabase.attachIndex(mIndex);
} else {
if (getLogger().isDebugEnabled()) {
this.getLogger().debug("initialize(): Datafile does not exist");
}
mDatabase = new IndexedObjectDatabase(databaseFile.toString(), false);
mIndex = new BTreeIndex(indexFile.toString(),
mOrder, new JispStringKey(), false);
mDatabase.attachIndex(mIndex);
}
} catch (KeyNotFound ignore) {
} catch (Exception e) {
getLogger().error("initialize(..) Exception", e);
}
}
/**
* Returns the repository's full pathname
*
* @return the directory as String
*/
public String getDirectoryPath() {
return this.directoryPath;
}
/**
* Returns a Object from the store associated with the Key Object
*
* @param key the Key object
* @return the Object associated with Key Object
*/
public Object get(Object key) {
Object value = null;
try {
value = mDatabase.read(this.wrapKeyObject(key), mIndex);
if (getLogger().isDebugEnabled()) {
if (value != null) {
getLogger().debug("Found key: " + key);
} else {
getLogger().debug("NOT Found key: " + key);
}
}
} catch (Exception e) {
getLogger().error("get(..): Exception", e);
}
return value;
}
/**
* Store the given object in the indexed data file.
*
* @param key the key object
* @param value the value object
* @exception IOException
*/
public void store(Object key, Object value)
throws IOException {
if (getLogger().isDebugEnabled()) {
this.getLogger().debug("store(): Store file with key: "
+ key.toString());
this.getLogger().debug("store(): Store file with value: "
+ value.toString());
}
if (value instanceof Serializable) {
try {
KeyObject[] keyArray = new KeyObject[1];
keyArray[0] = this.wrapKeyObject(key);
mDatabase.write(keyArray, (Serializable) value);
} catch (Exception e) {
this.getLogger().error("store(..): Exception", e);
}
} else {
throw new IOException("Object not Serializable");
}
}
/**
* Holds the given object in the indexed data file.
*
* @param key the key object
* @param value the value object
* @exception IOException
*/
public void hold(Object key, Object value)
throws IOException {
this.store(key, value);
}
/**
* Frees some values of the data file.<br>
* TODO: implementation
*/
public void free() {
//TODO: implementation
}
/**
* Removes a value from the data file with the given key.
*
* @param key the key object
*/
public void remove(Object key) {
if (getLogger().isDebugEnabled()) {
this.getLogger().debug("remove(..) Remove item");
}
try {
KeyObject[] keyArray = new KeyObject[1];
keyArray[0] = this.wrapKeyObject(key);
mDatabase.remove(keyArray);
} catch (KeyNotFound ignore) {
} catch (Exception e) {
this.getLogger().error("remove(..): Exception", e);
}
}
/**
* Test if the the index file contains the given key
*
* @param key the key object
* @return true if Key exists and false if not
*/
public boolean containsKey(Object key) {
long res = -1;
try {
res = mIndex.findKey(this.wrapKeyObject(key));
if (getLogger().isDebugEnabled()) {
this.getLogger().debug("containsKey(..): res=" + res);
}
} catch (KeyNotFound ignore) {
} catch (Exception e) {
this.getLogger().error("containsKey(..): Exception", e);
}
if (res > 0) {
return true;
} else {
return false;
}
}
/**
* Returns a Enumeration of all Keys in the indexed file.<br>
*
* @return Enumeration Object with all existing keys
*/
public Enumeration keys() {
// TODO: Implementation
return new Vector(0).elements();
}
public int size() {
// TODO: Unsupported
return 0;
}
/**
* This method wraps around the key Object a Jisp KeyObject.
*
* @param key the key object
* @return the wrapped key object
*/
private KeyObject wrapKeyObject(Object key) {
// TODO: Implementation of Integer and Long keys
String skey = String.valueOf(key);
return new JispStringKey(key.toString());
}
}