01: package net.sourceforge.jaxor.util;
02:
03: import net.sourceforge.jaxor.LazyLoader;
04: import net.sourceforge.jaxor.ReferenceResolver;
05: import net.sourceforge.jaxor.MetaField;
06: import net.sourceforge.jaxor.EntityRow;
07: import net.sourceforge.jaxor.api.EntityInterface;
08: import net.sourceforge.jaxor.api.EntityListAdapter;
09:
10: import java.util.List;
11: import java.util.Iterator;
12: import java.util.ArrayList;
13:
14: /**
15: * Created By: Mike
16: * Date: Feb 14, 2004
17: * Time: 4:46:19 PM
18: *
19: * Last Checkin: $Author: mrettig $
20: * Date: $Date: 2004/03/03 04:42:10 $
21: * Revision: $Revision: 1.2 $
22: */
23: public class ForeignFieldLazyLoader extends LazyLoader {
24:
25: private final ReferenceResolver _resolver;
26:
27: public ForeignFieldLazyLoader(Class finderClass, EntityRow parent,
28: boolean unique) {
29: this (new ReferenceResolver(finderClass, parent, unique));
30: }
31:
32: public ForeignFieldLazyLoader(ReferenceResolver keys) {
33: _resolver = keys;
34: }
35:
36: public void addKey(MetaField sourceField, MetaField targetField) {
37: getResolver().add(sourceField, targetField);
38: }
39:
40: public ReferenceResolver getResolver() {
41: return _resolver;
42: }
43:
44: protected Object resolve() {
45: return _resolver.getObject();
46: }
47:
48: public void setValue(Object result) {
49: super .setValue(result);
50: if (result == null)
51: return;
52: if (getResolver().isUnique())
53: syncSourceFieldsWithTarget(result);
54: }
55:
56: /**
57: * Field may resolve to a single entity or an entity list. This will always
58: * return a list to make working with the entities easier;
59: * @return
60: */
61: public List getFieldAsList() {
62: if (getResolver().isUnique()) {
63: List result = new ArrayList();
64: Object value = getValue();
65: if (value != null)
66: result.add(value);
67: return result;
68: }
69: return ((EntityListAdapter) getValue()).toList();
70: }
71:
72: private void syncSourceFieldsWithTarget(Object result) {
73: List keys = getResolver().getKeys();
74: EntityRow targetEntity = ((EntityInterface) result).getFields();
75: EntityRow sourceEntity = getResolver().getSourceEntity();
76: for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
77: ReferenceResolver.MetaPair metaPair = (ReferenceResolver.MetaPair) iterator
78: .next();
79: String sourceProperty = metaPair.Source.getProperty();
80: String targetProperty = metaPair.Target.getProperty();
81: sourceEntity.setPropertyValue(sourceProperty, targetEntity
82: .getPropertyValue(targetProperty));
83: }
84: }
85: }
|