3 import java
.beans
.PropertyDescriptor
;
4 import java
.io
.InputStream
;
5 import java
.util
.ArrayList
;
6 import java
.util
.Calendar
;
8 import java
.util
.GregorianCalendar
;
9 import java
.util
.HashMap
;
10 import java
.util
.List
;
12 import java
.util
.StringTokenizer
;
14 import javax
.jcr
.ItemNotFoundException
;
15 import javax
.jcr
.Node
;
16 import javax
.jcr
.NodeIterator
;
17 import javax
.jcr
.Property
;
18 import javax
.jcr
.PropertyIterator
;
19 import javax
.jcr
.PropertyType
;
20 import javax
.jcr
.RepositoryException
;
21 import javax
.jcr
.Session
;
22 import javax
.jcr
.Value
;
23 import javax
.jcr
.ValueFactory
;
25 import org
.apache
.commons
.logging
.Log
;
26 import org
.apache
.commons
.logging
.LogFactory
;
27 import org
.argeo
.ArgeoException
;
28 import org
.springframework
.beans
.BeanWrapper
;
29 import org
.springframework
.beans
.BeanWrapperImpl
;
31 public class BeanNodeMapper
{
32 private final static Log log
= LogFactory
.getLog(BeanNodeMapper
.class);
34 private final static String NODE_VALUE
= "value";
36 // private String keyNode = "bean:key";
37 private String uuidProperty
= "uuid";
38 private String classProperty
= "class";
40 private Boolean versioning
= false;
41 private Boolean strictUuidReference
= false;
42 private String primaryNodeType
= null;
44 private ClassLoader classLoader
= getClass().getClassLoader();
46 public String
storagePath(Object obj
) {
47 String clss
= obj
.getClass().getName();
48 StringBuffer buf
= new StringBuffer("/objects/");
49 StringTokenizer st
= new StringTokenizer(clss
, ".");
50 while (st
.hasMoreTokens()) {
51 buf
.append(st
.nextToken()).append('/');
53 buf
.append(obj
.toString());
54 return buf
.toString();
57 public Node
save(Session session
, Object obj
) {
58 return save(session
, storagePath(obj
), obj
);
61 public void update(Node node
, Object obj
) {
63 beanToNode(createBeanWrapper(obj
), node
);
64 } catch (RepositoryException e
) {
65 throw new ArgeoException("Cannot update node " + node
+ " with "
70 public Node
save(Session session
, String path
, Object obj
) {
72 BeanWrapper beanWrapper
= createBeanWrapper(obj
);
74 String parentPath
= JcrUtils
.parentPath(path
);
75 // find or create parent node
77 if (session
.itemExists(path
))
78 parentNode
= (Node
) session
.getItem(parentPath
);
80 parentNode
= JcrUtils
.mkdirs(session
, parentPath
, null,
83 if (primaryNodeType
!= null)
84 node
= parentNode
.addNode(JcrUtils
.lastPathElement(path
),
87 node
= parentNode
.addNode(JcrUtils
.lastPathElement(path
));
89 beanToNode(beanWrapper
, node
);
91 } catch (ArgeoException e
) {
93 } catch (Exception e
) {
94 throw new ArgeoException("Cannot save or update " + obj
+ " under "
99 @SuppressWarnings("unchecked")
100 public Object
nodeToBean(Node node
) throws RepositoryException
{
102 String clssName
= node
.getProperty(classProperty
).getValue()
105 if (log
.isTraceEnabled())
106 log
.debug("Map node " + node
.getPath() + " to bean " + clssName
);
108 BeanWrapper beanWrapper
= createBeanWrapper(loadClass(clssName
));
110 // process properties
111 PropertyIterator propIt
= node
.getProperties();
112 props
: while (propIt
.hasNext()) {
113 Property prop
= propIt
.nextProperty();
114 if (!beanWrapper
.isWritableProperty(prop
.getName()))
117 PropertyDescriptor pd
= beanWrapper
.getPropertyDescriptor(prop
119 Class propClass
= pd
.getPropertyType();
122 if (propClass
!= null && List
.class.isAssignableFrom(propClass
)) {
123 List
<Object
> lst
= new ArrayList
<Object
>();
124 Class
<?
> valuesClass
= classFromProperty(prop
);
125 if (valuesClass
!= null)
126 for (Value value
: prop
.getValues()) {
127 lst
.add(asObject(value
, valuesClass
));
132 Object value
= asObject(prop
.getValue(), pd
.getPropertyType());
134 beanWrapper
.setPropertyValue(prop
.getName(), value
);
137 // process children nodes
138 NodeIterator nodeIt
= node
.getNodes();
139 nodes
: while (nodeIt
.hasNext()) {
140 Node childNode
= nodeIt
.nextNode();
141 String name
= childNode
.getName();
142 if (!beanWrapper
.isWritableProperty(name
))
145 PropertyDescriptor pd
= beanWrapper
.getPropertyDescriptor(name
);
146 Class propClass
= pd
.getPropertyType();
148 if (propClass
!= null && List
.class.isAssignableFrom(propClass
)) {
149 String lstClass
= childNode
.getProperty(classProperty
)
153 lst
= (List
<Object
>) loadClass(lstClass
).newInstance();
154 } catch (Exception e
) {
155 lst
= new ArrayList
<Object
>();
158 NodeIterator valuesIt
= childNode
.getNodes();
159 while (valuesIt
.hasNext()) {
160 Node lstValueNode
= valuesIt
.nextNode();
161 Object lstValue
= nodeToBean(lstValueNode
);
165 beanWrapper
.setPropertyValue(name
, lst
);
169 if (propClass
!= null && Map
.class.isAssignableFrom(propClass
)) {
170 String mapClass
= childNode
.getProperty(classProperty
)
172 Map
<Object
, Object
> map
;
174 map
= (Map
<Object
, Object
>) loadClass(mapClass
)
176 } catch (Exception e
) {
177 map
= new HashMap
<Object
, Object
>();
181 PropertyIterator keysPropIt
= childNode
.getProperties();
182 keyProps
: while (keysPropIt
.hasNext()) {
183 Property keyProp
= keysPropIt
.nextProperty();
184 // FIXME: use property editor
185 String key
= keyProp
.getName();
186 if (classProperty
.equals(key
))
189 Class keyPropClass
= classFromProperty(keyProp
);
190 if (keyPropClass
!= null) {
191 Object mapValue
= asObject(keyProp
.getValue(),
193 map
.put(key
, mapValue
);
198 NodeIterator keysIt
= childNode
.getNodes();
199 while (keysIt
.hasNext()) {
200 Node mapValueNode
= keysIt
.nextNode();
201 // FIXME: use property editor
202 Object key
= mapValueNode
.getName();
204 Object mapValue
= nodeToBean(mapValueNode
);
206 map
.put(key
, mapValue
);
208 beanWrapper
.setPropertyValue(name
, map
);
213 Object value
= nodeToBean(childNode
);
214 beanWrapper
.setPropertyValue(name
, value
);
217 return beanWrapper
.getWrappedInstance();
220 protected void beanToNode(BeanWrapper beanWrapper
, Node node
)
221 throws RepositoryException
{
222 if (log
.isTraceEnabled())
223 log
.debug("Map bean to node " + node
.getPath());
225 properties
: for (PropertyDescriptor pd
: beanWrapper
226 .getPropertyDescriptors()) {
227 String name
= pd
.getName();
229 if (!beanWrapper
.isReadableProperty(name
))
230 continue properties
;// skip
232 Object value
= beanWrapper
.getPropertyValue(name
);
234 // remove values when updating
235 if (node
.hasProperty(name
))
236 node
.setProperty(name
, (Value
) null);
237 if (node
.hasNode(name
))
238 node
.getNode(name
).remove();
243 // if (uuidProperty != null && uuidProperty.equals(name)) {
244 // // node.addMixin(ArgeoJcrConstants.MIX_REFERENCEABLE);
245 // node.setProperty(ArgeoJcrConstants.JCR_UUID, value.toString());
246 // continue properties;
249 if ("class".equals(name
)) {
250 if (classProperty
!= null) {
251 node
.setProperty(classProperty
, ((Class
<?
>) value
)
253 // TODO: store a class hierarchy?
258 if (value
instanceof Class
<?
>) {
259 node
.setProperty(name
, ((Class
<?
>) value
).getName());
263 Value val
= asValue(node
.getSession(), value
);
265 node
.setProperty(name
, val
);
269 if (value
instanceof List
<?
>) {
270 List
<?
> lst
= (List
<?
>) value
;
271 addList(node
, name
, lst
);
275 if (value
instanceof Map
<?
, ?
>) {
276 Map
<?
, ?
> map
= (Map
<?
, ?
>) value
;
277 addMap(node
, name
, map
);
281 BeanWrapper child
= createBeanWrapper(value
);
282 // TODO: delegate to another mapper
284 // TODO: deal with references
285 // Node childNode = findChildReference(session, child);
286 // if (childNode != null) {
287 // node.setProperty(name, childNode);
288 // continue properties;
291 // default case (recursive)
292 if (node
.hasNode(name
)) {// update
294 node
.getNode(name
).remove();
296 Node childNode
= node
.addNode(name
);
297 beanToNode(child
, childNode
);
301 protected void addList(Node node
, String name
, List
<?
> lst
)
302 throws RepositoryException
{
303 if (node
.hasNode(name
)) {// update
305 node
.getNode(name
).remove();
308 Node listNode
= node
.addNode(name
);
309 listNode
.setProperty(classProperty
, lst
.getClass().getName());
310 Value
[] values
= new Value
[lst
.size()];
311 boolean atLeastOneSet
= false;
312 for (int i
= 0; i
< lst
.size(); i
++) {
313 Object lstValue
= lst
.get(i
);
314 values
[i
] = asValue(node
.getSession(), lstValue
);
315 if (values
[i
] != null) {
316 atLeastOneSet
= true;
318 Node childNode
= findChildReference(node
.getSession(),
319 createBeanWrapper(lstValue
));
320 if (childNode
!= null) {
321 values
[i
] = node
.getSession().getValueFactory()
322 .createValue(childNode
);
323 atLeastOneSet
= true;
328 // will be either properties or nodes, not both
329 if (!atLeastOneSet
&& lst
.size() != 0) {
330 for (Object lstValue
: lst
) {
331 Node childNode
= listNode
.addNode(NODE_VALUE
);
332 beanToNode(createBeanWrapper(lstValue
), childNode
);
335 listNode
.setProperty(name
, values
);
339 protected void addMap(Node node
, String name
, Map
<?
, ?
> map
)
340 throws RepositoryException
{
341 if (node
.hasNode(name
)) {// update
343 node
.getNode(name
).remove();
346 Node mapNode
= node
.addNode(name
);
347 mapNode
.setProperty(classProperty
, map
.getClass().getName());
348 for (Object key
: map
.keySet()) {
349 Object mapValue
= map
.get(key
);
350 // PropertyEditor pe = beanWrapper.findCustomEditor(key.getClass(),
354 if (key
instanceof CharSequence
)
355 keyStr
= key
.toString();
357 throw new ArgeoException(
358 "Cannot find property editor for class "
362 // keyStr = pe.getAsText();
364 // TODO: check string format
366 Value mapVal
= asValue(node
.getSession(), mapValue
);
368 mapNode
.setProperty(keyStr
, mapVal
);
370 Node entryNode
= mapNode
.addNode(keyStr
);
371 beanToNode(createBeanWrapper(mapValue
), entryNode
);
378 protected BeanWrapper
createBeanWrapper(Object obj
) {
379 return new BeanWrapperImpl(obj
);
382 protected BeanWrapper
createBeanWrapper(Class
<?
> clss
) {
383 return new BeanWrapperImpl(clss
);
386 /** Returns null if value cannot be found */
387 protected Value
asValue(Session session
, Object value
)
388 throws RepositoryException
{
389 ValueFactory valueFactory
= session
.getValueFactory();
390 if (value
instanceof Integer
)
391 return valueFactory
.createValue((Integer
) value
);
392 else if (value
instanceof Long
)
393 return valueFactory
.createValue((Long
) value
);
394 else if (value
instanceof Float
)
395 return valueFactory
.createValue((Float
) value
);
396 else if (value
instanceof Double
)
397 return valueFactory
.createValue((Double
) value
);
398 else if (value
instanceof Boolean
)
399 return valueFactory
.createValue((Boolean
) value
);
400 else if (value
instanceof Calendar
)
401 return valueFactory
.createValue((Calendar
) value
);
402 else if (value
instanceof Date
) {
403 Calendar cal
= new GregorianCalendar();
404 cal
.setTime((Date
) value
);
405 return valueFactory
.createValue(cal
);
406 } else if (value
instanceof CharSequence
)
407 return valueFactory
.createValue(value
.toString());
408 else if (value
instanceof InputStream
)
409 return valueFactory
.createValue((InputStream
) value
);
414 protected Class
<?
> classFromProperty(Property property
)
415 throws RepositoryException
{
416 switch (property
.getType()) {
417 case PropertyType
.LONG
:
419 case PropertyType
.DOUBLE
:
421 case PropertyType
.STRING
:
423 case PropertyType
.BOOLEAN
:
424 return Boolean
.class;
425 case PropertyType
.DATE
:
426 return Calendar
.class;
427 case PropertyType
.NAME
:
430 throw new ArgeoException("Cannot find class for property "
431 + property
+ ", type="
432 + PropertyType
.nameFromValue(property
.getType()));
436 protected Object
asObject(Value value
, Class
<?
> propClass
)
437 throws RepositoryException
{
438 if (propClass
.equals(Integer
.class))
439 return (int) value
.getLong();
440 else if (propClass
.equals(Long
.class))
441 return value
.getLong();
442 else if (propClass
.equals(Float
.class))
443 return (float) value
.getDouble();
444 else if (propClass
.equals(Double
.class))
445 return value
.getDouble();
446 else if (propClass
.equals(Boolean
.class))
447 return value
.getBoolean();
448 else if (CharSequence
.class.isAssignableFrom(propClass
))
449 return value
.getString();
450 else if (InputStream
.class.isAssignableFrom(propClass
))
451 return value
.getStream();
452 else if (Calendar
.class.isAssignableFrom(propClass
))
453 return value
.getDate();
454 else if (Date
.class.isAssignableFrom(propClass
))
455 return value
.getDate().getTime();
460 protected Node
findChildReference(Session session
, BeanWrapper child
)
461 throws RepositoryException
{
462 if (child
.isReadableProperty(uuidProperty
)) {
463 String childUuid
= child
.getPropertyValue(uuidProperty
).toString();
465 return session
.getNodeByUUID(childUuid
);
466 } catch (ItemNotFoundException e
) {
467 if (strictUuidReference
)
468 throw new ArgeoException("No node found with uuid "
475 protected Class
<?
> loadClass(String name
) {
476 //log.debug("Class loader: " + classLoader);
478 return classLoader
.loadClass(name
);
479 } catch (ClassNotFoundException e
) {
480 throw new ArgeoException("Cannot load class " + name
, e
);
484 protected String
propertyName(String name
) {
488 public void setVersioning(Boolean versioning
) {
489 this.versioning
= versioning
;
492 public void setUuidProperty(String uuidProperty
) {
493 this.uuidProperty
= uuidProperty
;
496 public void setClassProperty(String classProperty
) {
497 this.classProperty
= classProperty
;
500 public void setStrictUuidReference(Boolean strictUuidReference
) {
501 this.strictUuidReference
= strictUuidReference
;
504 public void setPrimaryNodeType(String primaryNodeType
) {
505 this.primaryNodeType
= primaryNodeType
;
508 public void setClassLoader(ClassLoader classLoader
) {
509 this.classLoader
= classLoader
;