01: package com.technoetic.xplanner.domain;
02:
03: import java.lang.reflect.InvocationTargetException;
04:
05: import net.sf.hibernate.HibernateException;
06: import net.sf.hibernate.Session;
07: import org.apache.commons.beanutils.PropertyUtils;
08:
09: import com.technoetic.xplanner.db.hibernate.ThreadSession;
10:
11: //DEBT(METADATA) Rename this class to illustrate its responsability
12:
13: /**
14: * @resp Convert a DTO (Form, SOAP data object) attribute to a Domain object relationship and vise-a-versa
15: */
16: public class RelationshipConvertor {
17: private String adapterProperty;
18: private String domainProperty;
19:
20: public RelationshipConvertor(String adapterProperty,
21: String domainObjectProperty) {
22: this .adapterProperty = adapterProperty;
23: this .domainProperty = domainObjectProperty;
24: }
25:
26: public String getAdapterProperty() {
27: return adapterProperty;
28: }
29:
30: public String getDomainProperty() {
31: return domainProperty;
32: }
33:
34: public void populateDomainObject(DomainObject target, Object adapter)
35: throws HibernateException, IllegalAccessException,
36: InvocationTargetException, NoSuchMethodException {
37: populateDomainObject(target, adapter, ThreadSession.get());
38: }
39:
40: public void populateDomainObject(DomainObject destination,
41: Object source, Session session) throws HibernateException,
42: IllegalAccessException, InvocationTargetException,
43: NoSuchMethodException {
44: if (PropertyUtils.isReadable(source, adapterProperty)
45: && PropertyUtils.isWriteable(destination,
46: domainProperty)) {
47: Integer referredId = (Integer) PropertyUtils.getProperty(
48: source, adapterProperty);
49: Class destinationType = PropertyUtils.getPropertyType(
50: destination, domainProperty);
51: Object referred = findObjectById(session, destinationType,
52: referredId);
53: PropertyUtils.setProperty(destination, domainProperty,
54: referred);
55: }
56: }
57:
58: private Object findObjectById(Session session, Class aClass,
59: Integer id) throws HibernateException {
60: if (id.intValue() == 0)
61: return null;
62: return session.load(aClass, id);
63: }
64:
65: public void populateAdapter(Object adapter,
66: DomainObject domainObject) throws NoSuchMethodException,
67: IllegalAccessException, InvocationTargetException {
68: Object referred = PropertyUtils.getProperty(domainObject,
69: domainProperty);
70: Integer id = referred == null ? new Integer(0)
71: : (Integer) PropertyUtils.getProperty(referred, "id");
72: PropertyUtils.setProperty(adapter, adapterProperty, id);
73: }
74:
75: }
|