001 package org.apache.ojb.broker.util.collections;
002
003 /* Copyright 2003-2005 The Apache Software Foundation
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 import java.util.HashMap;
019 import java.util.Iterator;
020
021 import org.apache.ojb.broker.ManageableCollection;
022 import org.apache.ojb.broker.PersistenceBroker;
023 import org.apache.ojb.broker.PersistenceBrokerException;
024 import org.apache.ojb.broker.metadata.ClassDescriptor;
025 import org.apache.ojb.broker.metadata.FieldDescriptor;
026 import org.apache.ojb.broker.metadata.MetadataException;
027 import org.apache.ojb.broker.metadata.MetadataManager;
028
029
030 /**
031 * Creates a Map where the primary key is the map key, and the object
032 * is the map value.
033 * <br/>
034 * <strong>Note:</strong> This implementation is limited in use, only objects with
035 * single primary key field are allowed (composed PK's are illegal).
036 */
037 public class ManageableHashMap extends HashMap implements ManageableCollection
038 {
039 public void ojbAdd(Object anObject)
040 {
041 if (anObject != null)
042 {
043 ClassDescriptor cd = MetadataManager.getInstance().getRepository().getDescriptorFor(anObject.getClass());
044 FieldDescriptor[] fields = cd.getPkFields();
045 if(fields.length > 1 || fields.length == 0)
046 {
047 throw new MetadataException("ManageableHashMap can only be used for persistence capable objects with" +
048 " exactly one primiary key field defined in metadata, for " + anObject.getClass() + " the" +
049 " PK field count is " + fields.length);
050 }
051 else
052 {
053 Object key = fields[0].getPersistentField().get(anObject);
054 put(key,anObject);
055 }
056 }
057 }
058
059 public void ojbAddAll(ManageableCollection otherCollection)
060 {
061 Iterator it = otherCollection.ojbIterator();
062 while (it.hasNext())
063 {
064 ojbAdd(it.next());
065 }
066 }
067
068 public Iterator ojbIterator()
069 {
070 return values().iterator();
071 }
072
073 public void afterStore(PersistenceBroker broker) throws PersistenceBrokerException
074 {
075 //do nothing
076 }
077 }