01: package org.apache.ojb.broker.util.collections;
02:
03: /* Copyright 2003-2005 The Apache Software Foundation
04: *
05: * Licensed under the Apache License, Version 2.0 (the "License");
06: * you may not use this file except in compliance with the License.
07: * You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: import java.util.HashMap;
19: import java.util.Iterator;
20:
21: import org.apache.ojb.broker.ManageableCollection;
22: import org.apache.ojb.broker.PersistenceBroker;
23: import org.apache.ojb.broker.PersistenceBrokerException;
24: import org.apache.ojb.broker.metadata.ClassDescriptor;
25: import org.apache.ojb.broker.metadata.FieldDescriptor;
26: import org.apache.ojb.broker.metadata.MetadataException;
27: import org.apache.ojb.broker.metadata.MetadataManager;
28:
29: /**
30: * Creates a Map where the primary key is the map key, and the object
31: * is the map value.
32: * <br/>
33: * <strong>Note:</strong> This implementation is limited in use, only objects with
34: * single primary key field are allowed (composed PK's are illegal).
35: */
36: public class ManageableHashMap extends HashMap implements
37: ManageableCollection {
38: public void ojbAdd(Object anObject) {
39: if (anObject != null) {
40: ClassDescriptor cd = MetadataManager.getInstance()
41: .getRepository().getDescriptorFor(
42: anObject.getClass());
43: FieldDescriptor[] fields = cd.getPkFields();
44: if (fields.length > 1 || fields.length == 0) {
45: throw new MetadataException(
46: "ManageableHashMap can only be used for persistence capable objects with"
47: + " exactly one primiary key field defined in metadata, for "
48: + anObject.getClass() + " the"
49: + " PK field count is " + fields.length);
50: } else {
51: Object key = fields[0].getPersistentField().get(
52: anObject);
53: put(key, anObject);
54: }
55: }
56: }
57:
58: public void ojbAddAll(ManageableCollection otherCollection) {
59: Iterator it = otherCollection.ojbIterator();
60: while (it.hasNext()) {
61: ojbAdd(it.next());
62: }
63: }
64:
65: public Iterator ojbIterator() {
66: return values().iterator();
67: }
68:
69: public void afterStore(PersistenceBroker broker)
70: throws PersistenceBrokerException {
71: //do nothing
72: }
73: }
|