01: package org.hibernate.tuple;
02:
03: import org.apache.commons.collections.SequencedHashMap;
04:
05: import org.hibernate.EntityMode;
06: import org.hibernate.HibernateException;
07:
08: import java.util.Map;
09: import java.util.Collections;
10: import java.util.Iterator;
11: import java.io.Serializable;
12:
13: /**
14: * Centralizes handling of {@link EntityMode} to {@link Tuplizer} mappings.
15: *
16: * @author Steve Ebersole
17: */
18: public abstract class EntityModeToTuplizerMapping implements
19: Serializable {
20:
21: // map of EntityMode -> Tuplizer
22: private final Map tuplizers = Collections
23: .synchronizedMap(new SequencedHashMap());
24:
25: protected void addTuplizer(EntityMode entityMode, Tuplizer tuplizer) {
26: tuplizers.put(entityMode, tuplizer);
27: }
28:
29: /**
30: * Given a supposed instance of an entity/component, guess its entity mode.
31: *
32: * @param object The supposed instance of the entity/component.
33: * @return The guessed entity mode.
34: */
35: public EntityMode guessEntityMode(Object object) {
36: Iterator itr = tuplizers.entrySet().iterator();
37: while (itr.hasNext()) {
38: Map.Entry entry = (Map.Entry) itr.next();
39: Tuplizer tuplizer = (Tuplizer) entry.getValue();
40: if (tuplizer.isInstance(object)) {
41: return (EntityMode) entry.getKey();
42: }
43: }
44: return null;
45: }
46:
47: /**
48: * Locate the contained tuplizer responsible for the given entity-mode. If
49: * no such tuplizer is defined on this mapping, then return null.
50: *
51: * @param entityMode The entity-mode for which the caller wants a tuplizer.
52: * @return The tuplizer, or null if not found.
53: */
54: public Tuplizer getTuplizerOrNull(EntityMode entityMode) {
55: return (Tuplizer) tuplizers.get(entityMode);
56: }
57:
58: /**
59: * Locate the tuplizer contained within this mapping which is responsible
60: * for the given entity-mode. If no such tuplizer is defined on this
61: * mapping, then an exception is thrown.
62: *
63: * @param entityMode The entity-mode for which the caller wants a tuplizer.
64: * @return The tuplizer.
65: * @throws HibernateException Unable to locate the requested tuplizer.
66: */
67: public Tuplizer getTuplizer(EntityMode entityMode) {
68: Tuplizer tuplizer = getTuplizerOrNull(entityMode);
69: if (tuplizer == null) {
70: throw new HibernateException(
71: "No tuplizer found for entity-mode [" + entityMode
72: + "]");
73: }
74: return tuplizer;
75: }
76: }
|