/**********************************************************************
Copyright (c) 2004 Andy Jefferson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
2004 Andy Jefferson - added Queryable implementation
...
**********************************************************************/
package org.jpox.sco;
import java.io.ObjectStreamException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import org.jpox.ClassLoaderResolver;
import org.jpox.ObjectManager;
import org.jpox.ObjectManagerFactoryImpl;
import org.jpox.StateManager;
import org.jpox.metadata.AbstractMemberMetaData;
import org.jpox.metadata.FieldPersistenceModifier;
import org.jpox.sco.exceptions.NullsNotAllowedException;
import org.jpox.sco.exceptions.QueryUnownedSCOException;
import org.jpox.sco.queued.ClearOperation;
import org.jpox.sco.queued.PutOperation;
import org.jpox.sco.queued.QueuedOperation;
import org.jpox.sco.queued.RemoveOperation;
import org.jpox.state.FetchPlanState;
import org.jpox.state.StateManagerFactory;
import org.jpox.store.mapped.DatastoreIdentifier;
import org.jpox.store.mapped.expression.QueryExpression;
import org.jpox.store.mapped.query.Queryable;
import org.jpox.store.mapped.scostore.MapStoreQueryable;
import org.jpox.store.query.ResultObjectFactory;
import org.jpox.store.scostore.MapStore;
import org.jpox.util.JPOXLogger;
import org.jpox.util.Localiser;
import org.jpox.util.StringUtils;
/**
* A mutable second-class Hashtable object. Backed by a MapStore object.
*
* @version $Revision: 1.86 $
*/
public class Hashtable extends java.util.Hashtable
implements SCOMap, Cloneable, Queryable
{
protected static final Localiser LOCALISER = Localiser.getInstance("org.jpox.Localisation",
ObjectManagerFactoryImpl.class.getClassLoader());
private transient Object owner;
private transient StateManager ownerSM;
private transient String fieldName;
private transient int fieldNumber;
private transient Class valueType;
private transient boolean allowNulls;
/** The "backing store" */
protected MapStore backingStore;
/** The internal "delegate". */
protected java.util.Hashtable delegate;
/** Whether to use "delegate" caching. */
protected boolean useCache=true;
/** Status flag whether the map is loaded into the cache. */
protected boolean isCacheLoaded=false;
/** Whether the SCO is in "direct" or "queued" mode. */
boolean queued = false;
/** Queued operations when using "queued" mode. */
private java.util.ArrayList queuedOperations = null;
/**
* Constructor
* @param ownerSM the owner of this Map
* @param fieldName the declared field name
*/
public Hashtable(StateManager ownerSM, String fieldName)
{
this.ownerSM = ownerSM;
this.fieldName = fieldName;
this.allowNulls = false; // Underlying Hashtable prohibits null keys/values
// Set up our "delegate"
this.delegate = new java.util.Hashtable();
if (ownerSM != null)
{
AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
owner = ownerSM.getObject();
fieldNumber = fmd.getAbsoluteFieldNumber();
if (ownerSM.getStoreManager().getSupportedOptions().contains("ContainerQueueing"))
{
queued = SCOUtils.useContainerQueueing(ownerSM);
useCache = SCOUtils.useContainerCache(ownerSM, fieldName);
}
if (!SCOUtils.mapHasSerialisedKeysAndValues(fmd) &&
fmd.getPersistenceModifier() == FieldPersistenceModifier.PERSISTENT)
{
try
{
ClassLoaderResolver clr = ownerSM.getObjectManager().getClassLoaderResolver();
this.backingStore = (MapStore) ownerSM.getStoreManager().getBackingStoreForField(clr, fmd, java.util.Hashtable.class);
this.valueType = clr.classForName(this.backingStore.getValueType());
}
catch(UnsupportedOperationException ex)
{
//some datastores do not support backingStores
}
}
if (JPOXLogger.PERSISTENCE.isDebugEnabled())
{
JPOXLogger.PERSISTENCE.debug(SCOUtils.getContainerInfoMessage(ownerSM, fieldName, this,
useCache, queued, allowNulls, SCOUtils.useCachedLazyLoading(ownerSM, fieldName)));
}
}
}
/**
* Method to initialise the SCO from an existing value.
* @param o Object to set value using.
* @param forInsert Whether the object needs inserting in the datastore with this value
* @param forUpdate Whether to update the datastore with this value
*/
public void initialise(Object o, boolean forInsert, boolean forUpdate)
{
java.util.Map m = (java.util.Map)o;
if (m != null)
{
// Check for the case of serialised maps, and assign StateManagers to any PC keys/values without
AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
if (SCOUtils.mapHasSerialisedKeysAndValues(fmd) &&
(fmd.getMap().getKeyClassMetaData() != null || fmd.getMap().getValueClassMetaData() != null))
{
ObjectManager om = ownerSM.getObjectManager();
Iterator iter = m.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (fmd.getMap().getKeyClassMetaData() != null)
{
StateManager objSM = om.findStateManager(key);
if (objSM == null)
{
objSM = StateManagerFactory.newStateManagerForEmbedded(om, key, false);
objSM.addEmbeddedOwner(ownerSM, fieldNumber);
}
}
if (fmd.getMap().getValueClassMetaData() != null)
{
StateManager objSM = om.findStateManager(value);
if (objSM == null)
{
objSM = StateManagerFactory.newStateManagerForEmbedded(om, value, false);
objSM.addEmbeddedOwner(ownerSM, fieldNumber);
}
}
}
}
if (backingStore != null && useCache && !isCacheLoaded)
{
// Mark as loaded
isCacheLoaded = true;
}
if (forInsert)
{
if (JPOXLogger.PERSISTENCE.isDebugEnabled())
{
JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023007",
StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + m.size()));
}
putAll(m);
}
else if (forUpdate)
{
if (JPOXLogger.PERSISTENCE.isDebugEnabled())
{
JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023008",
StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + m.size()));
}
clear();
putAll(m);
}
else
{
if (JPOXLogger.PERSISTENCE.isDebugEnabled())
{
JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023007",
StringUtils.toJVMIDString(ownerSM.getObject()), fieldName, "" + m.size()));
}
delegate.clear();
delegate.putAll(m);
}
}
}
/**
* Method to initialise the SCO for use.
*/
public void initialise()
{
if (useCache && !SCOUtils.useCachedLazyLoading(ownerSM, fieldName))
{
// Load up the container now if not using lazy loading
loadFromStore();
}
}
/**
* Accessor for the unwrapped value that we are wrapping.
* @return The unwrapped value
*/
public Object getValue()
{
// TODO Cater for delegate not being used
return delegate;
}
/**
* Method to effect the load of the data in the SCO.
* Used when the SCO supports lazy-loading to tell it to load all now.
*/
public void load()
{
if (useCache)
{
loadFromStore();
}
}
/**
* Method to load all elements from the "backing store" where appropriate.
*/
protected void loadFromStore()
{
if (backingStore != null && !isCacheLoaded)
{
if (JPOXLogger.PERSISTENCE.isDebugEnabled())
{
JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023006",
StringUtils.toJVMIDString(ownerSM.getObject()), fieldName));
}
delegate.clear();
// Populate the delegate with the keys/values from the store
SCOUtils.populateMapDelegateWithStoreData(delegate, backingStore, ownerSM);
isCacheLoaded = true;
}
}
/**
* Method to flush the changes to the datastore when operating in queued mode.
* Does nothing in "direct" mode.
*/
public void flush()
{
if (queued)
{
if (queuedOperations != null)
{
if (JPOXLogger.PERSISTENCE.isDebugEnabled())
{
JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023005",
StringUtils.toJVMIDString(ownerSM.getObject()), fieldName));
}
Iterator iter = queuedOperations.iterator();
while (iter.hasNext())
{
QueuedOperation op = (QueuedOperation)iter.next();
op.perform(backingStore, ownerSM);
}
queuedOperations.clear();
queuedOperations = null;
}
}
}
/**
* Convenience method to add a queued operation to the operations we perform at commit.
* @param op The operation
*/
protected void addQueuedOperation(QueuedOperation op)
{
if (queuedOperations == null)
{
queuedOperations = new java.util.ArrayList();
}
queuedOperations.add(op);
}
/**
* Method to update an embedded key in this map.
* @param key The key
* @param fieldNumber Number of field in the key
* @param newValue New value for this field
*/
public void updateEmbeddedKey(Object key, int fieldNumber, Object newValue)
{
if (backingStore != null)
{
backingStore.updateEmbeddedKey(ownerSM, key, fieldNumber, newValue);
}
}
/**
* Method to update an embedded value in this map.
* @param value The value
* @param fieldNumber Number of field in the value
* @param newValue New value for this field
*/
public void updateEmbeddedValue(Object value, int fieldNumber, Object newValue)
{
if (backingStore != null)
{
backingStore.updateEmbeddedValue(ownerSM, value, fieldNumber, newValue);
}
}
/**
* Accessor for the field name that this Hashtable relates to.
* @return The field name
**/
public String getFieldName()
{
return fieldName;
}
/**
* Accessor for the owner that this Hashtable relates to.
* @return The owner
**/
public Object getOwner()
{
return owner;
}
/**
* Method to unset the owner and field details.
**/
public synchronized void unsetOwner()
{
if (ownerSM != null)
{
owner = null;
ownerSM = null;
fieldName = null;
backingStore = null;
}
}
/**
* Utility to mark the object as dirty
**/
public void makeDirty()
{
// Although we are never really "dirty", the owning object must be
// marked dirty so that the proper state change occurs and its
// jdoPreStore() gets called properly.
if (ownerSM != null)
{
ownerSM.getObjectManager().getApiAdapter().makeFieldDirty(owner, fieldName);
}
}
/**
* Method to return a detached copy of the container.
* Recurse sthrough the keys/values so that they are likewise detached.
* @param state State for detachment process
* @return The detached container
*/
public Object detachCopy(FetchPlanState state)
{
java.util.Map detached = new java.util.Hashtable();
SCOUtils.detachCopyForMap(ownerSM, entrySet(), state, detached);
return detached;
}
/**
* Method to return an attached copy of the passed (detached) value. The returned attached copy
* is a SCO wrapper. Goes through the existing keys/values in the store for this owner field and
* removes ones no longer present, and adds new keys/values. All keys/values in the (detached)
* value are attached.
* @param value The new (map) value
*/
public void attachCopy(Object value)
{
java.util.Map m = (java.util.Map) value;
// Attach all of the keys/values in the new map
AbstractMemberMetaData fmd = ownerSM.getClassMetaData().getMetaDataForMember(fieldName);
boolean keysWithoutIdentity = SCOUtils.mapHasKeysWithoutIdentity(fmd);
boolean valuesWithoutIdentity = SCOUtils.mapHasValuesWithoutIdentity(fmd);
java.util.Map attachedKeysValues = new java.util.HashMap(m.size());
SCOUtils.attachCopyForMap(ownerSM, m.entrySet(), attachedKeysValues, keysWithoutIdentity, valuesWithoutIdentity);
// Update the attached map with the detached elements
SCOUtils.updateMapWithMapKeysValues(ownerSM.getObjectManager().getApiAdapter(), this, attachedKeysValues);
}
// ------------------------- Queryable Methods -----------------------------
/**
* Method to generate a QueryStatement for the SCO.
* @return The QueryStatement
*/
public synchronized QueryExpression newQueryStatement()
{
return newQueryStatement(valueType, null);
}
/**
* Method to return a QueryStatement, using the specified candidate class.
* @param candidateClass the candidate class
* @param candidateAlias Alias for the candidate
* @return The QueryStatement
*/
public synchronized QueryExpression newQueryStatement(Class candidateClass, DatastoreIdentifier candidateAlias)
{
if (backingStore == null)
{
throw new QueryUnownedSCOException();
}
return ((MapStoreQueryable)backingStore).newQueryStatement(ownerSM, candidateClass.getName(), candidateAlias);
}
/**
* Method to return a new result object factory for processing of Query
* statements.
* @param stmt The Query Statement.
* @param ignoreCache Whether to ignore the cache.
* @param resultClass Whether to create objects of a particular class
* @param useFetchPlan whether to use the fetch plan to retrieve fields in the same query
* @return The result object factory.
**/
public synchronized ResultObjectFactory newResultObjectFactory(
QueryExpression stmt,
boolean ignoreCache,
Class resultClass,
boolean useFetchPlan)
{
if (backingStore == null)
{
throw new QueryUnownedSCOException();
}
return ((MapStoreQueryable)backingStore).newResultObjectFactory(ownerSM, stmt,ignoreCache,useFetchPlan);
}
// ------------------ Implementation of Hashtable methods ------------------
/**
* Creates and returns a copy of this object.
*
* <P>Mutable second-class Objects are required to provide a public
* clone method in order to allow for copying PersistenceCapable
* objects. In contrast to Object.clone(), this method must not throw a
* CloneNotSupportedException.
* @return The cloned object
*/
public Object clone()
{
if (useCache)
{
loadFromStore();
}
return delegate.clone();
}
/**
* Method to return if the map contains this key
* @param key The key
* @return Whether it is contained
**/
public boolean containsKey(Object key)
{
if (useCache && isCacheLoaded)
{
// If the "delegate" is already loaded, use it
return delegate.containsKey(key);
}
else if (backingStore != null)
{
return backingStore.containsKey(ownerSM, key);
}
return delegate.containsKey(key);
}
/**
* Method to return if the map contains this value.
* @param value The value
* @return Whether it is contained
**/
public boolean containsValue(Object value)
{
if (useCache && isCacheLoaded)
{
// If the "delegate" is already loaded, use it
return delegate.containsValue(value);
}
else if (backingStore != null)
{
return backingStore.containsValue(ownerSM, value);
}
return delegate.containsValue(value);
}
/**
* Accessor for the set of entries in the Map.
* @return Set of entries
**/
public java.util.Set entrySet()
{
if (useCache)
{
loadFromStore();
}
else if (backingStore != null)
{
return new Set(ownerSM, fieldName, false, backingStore.entrySetStore());
}
return delegate.entrySet();
}
/**
* Method to check the equality of this map, and another.
* @param o The map to compare against.
* @return Whether they are equal.
**/
public synchronized boolean equals(Object o)
{
if (useCache)
{
loadFromStore();
}
if (o == this)
{
return true;
}
if (!(o instanceof java.util.Map))
{
return false;
}
java.util.Map m = (java.util.Map)o;
return entrySet().equals(m.entrySet());
}
/**
* Accessor for the value stored against a key.
* @param key The key
* @return The value.
**/
public Object get(Object key)
{
if (useCache)
{
loadFromStore();
}
else if (backingStore != null)
{
return backingStore.get(ownerSM, key);
}
return delegate.get(key);
}
/**
* Method to generate a hashcode for this Map.
* @return The hashcode.
**/
public synchronized int hashCode()
{
if (useCache)
{
loadFromStore();
}
else if (backingStore != null)
{
int h = 0;
Iterator i = entrySet().iterator();
while (i.hasNext())
{
h += i.next().hashCode();
}
return h;
}
return delegate.hashCode();
}
/**
* Method to return if the Map is empty.
* @return Whether it is empty.
**/
public boolean isEmpty()
{
return size() == 0;
}
/**
* Accessor for the set of keys in the Map.
* @return Set of keys.
**/
public java.util.Set keySet()
{
if (useCache)
{
loadFromStore();
}
else if (backingStore != null)
{
return new Set(ownerSM, fieldName, false, backingStore.keySetStore(ownerSM.getObjectManager().getClassLoaderResolver()));
}
return delegate.keySet();
}
/**
* Method to return the size of the Map.
* @return The size
**/
public int size()
{
if (useCache && isCacheLoaded)
{
// If the "delegate" is already loaded, use it
return delegate.size();
}
else if (backingStore != null)
{
return backingStore.entrySetStore().size(ownerSM);
}
return delegate.size();
}
/**
* Accessor for the set of values in the Map.
* @return Set of values.
**/
public Collection values()
{
if (useCache)
{
loadFromStore();
}
else if (backingStore != null)
{
return new Set(ownerSM, fieldName, true, backingStore.valueSetStore(ownerSM.getObjectManager().getClassLoaderResolver()));
}
return delegate.values();
}
// -------------------------------- Mutator methods ------------------------
/**
* Method to clear the Hashtable
**/
public synchronized void clear()
{
makeDirty();
if (backingStore != null)
{
if (queued && !ownerSM.getObjectManager().isFlushing())
{
addQueuedOperation(new ClearOperation());
}
else
{
backingStore.clear(ownerSM);
}
}
delegate.clear();
}
/**
* Method to add a value against a key to the Hashtable
* @param key The key
* @param value The value
* @return The previous value for the specified key.
**/
public Object put(Object key,Object value)
{
// Reject inappropriate elements
if (value == null && !allowNulls)
{
throw new NullsNotAllowedException(ownerSM, fieldName);
}
if (useCache)
{
loadFromStore();
}
makeDirty();
Object oldValue = null;
if (backingStore != null)
{
if (queued && !ownerSM.getObjectManager().isFlushing())
{
addQueuedOperation(new PutOperation(key, value));
}
else
{
oldValue = backingStore.put(ownerSM, key, value);
}
}
Object delegateOldValue = delegate.put(key, value);
if (backingStore == null)
{
oldValue = delegateOldValue;
}
else if (queued && !ownerSM.getObjectManager().isFlushing())
{
oldValue = delegateOldValue;
}
return oldValue;
}
/**
* Method to add the specified Map's values under their keys here.
* @param m The map
**/
public void putAll(java.util.Map m)
{
makeDirty();
if (useCache)
{
loadFromStore();
}
if (backingStore != null)
{
if (queued && !ownerSM.getObjectManager().isFlushing())
{
Iterator iter = m.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
addQueuedOperation(new PutOperation(entry.getKey(), entry.getValue()));
}
}
else
{
backingStore.putAll(ownerSM, m);
}
}
delegate.putAll(m);
}
/**
* Method to remove the value for a key from the Hashtable
* @param key The key to remove
* @return The value that was removed from this key.
**/
public Object remove(Object key)
{
makeDirty();
if (useCache)
{
loadFromStore();
}
Object removed = null;
Object delegateRemoved = delegate.remove(key);
if (backingStore != null)
{
if (queued && !ownerSM.getObjectManager().isFlushing())
{
addQueuedOperation(new RemoveOperation(key));
removed = delegateRemoved;
}
else
{
removed = backingStore.remove(ownerSM, key);
}
}
else
{
removed = delegateRemoved;
}
return removed;
}
/**
* The writeReplace method is called when ObjectOutputStream is preparing
* to write the object to the stream. The ObjectOutputStream checks whether
* the class defines the writeReplace method. If the method is defined, the
* writeReplace method is called to allow the object to designate its
* replacement in the stream. The object returned should be either of the
* same type as the object passed in or an object that when read and
* resolved will result in an object of a type that is compatible with all
* references to the object.
*
* @return the replaced object
* @throws ObjectStreamException
*/
protected Object writeReplace() throws ObjectStreamException
{
if (useCache)
{
loadFromStore();
return new java.util.Hashtable(delegate);
}
else
{
// TODO Cater for non-cached map, load elements in a DB call.
return new java.util.Hashtable(delegate);
}
}
}