01: package org.geotools.xml.impl;
02:
03: import java.util.logging.Logger;
04:
05: import org.eclipse.xsd.XSDAttributeDeclaration;
06: import org.geotools.util.Converters;
07: import org.geotools.xml.Binding;
08: import org.geotools.xml.SimpleBinding;
09: import org.w3c.dom.Attr;
10: import org.w3c.dom.Document;
11:
12: public class AttributeEncodeExecutor implements BindingWalker.Visitor {
13:
14: /** the object being encoded **/
15: Object object;
16:
17: /** the attribute being encoded **/
18: XSDAttributeDeclaration attribute;
19:
20: /** the encoded value **/
21: Attr encoding;
22:
23: /** the document / factory **/
24: Document document;
25:
26: /** logger */
27: Logger logger;
28:
29: public AttributeEncodeExecutor(Object object,
30: XSDAttributeDeclaration attribute, Document document,
31: Logger logger) {
32: this .object = object;
33: this .attribute = attribute;
34: this .document = document;
35: this .logger = logger;
36:
37: encoding = document.createAttributeNS(attribute
38: .getTargetNamespace(), attribute.getName());
39:
40: }
41:
42: public Attr getEncodedAttribute() {
43: return encoding;
44: }
45:
46: public void visit(Binding binding) {
47: //ensure the object type matches the type declared on the bindign
48: if (binding.getType() == null) {
49: logger.warning("Binding: " + binding.getTarget()
50: + " does not declare a target type");
51: return;
52: }
53: if (!binding.getType().isAssignableFrom(object.getClass())) {
54: //try to convert
55: Object converted = Converters.convert(object, binding
56: .getType());
57: if (converted != null) {
58: object = converted;
59: } else {
60: logger.warning(object + "[ " + object.getClass()
61: + " ] is not of type " + binding.getType());
62: return;
63: }
64: }
65:
66: if (binding instanceof SimpleBinding) {
67: SimpleBinding simple = (SimpleBinding) binding;
68:
69: try {
70: encoding.setValue(simple.encode(object, encoding
71: .getValue()));
72: } catch (Throwable t) {
73: String msg = "Encode failed for " + attribute.getName()
74: + ". Cause: " + t.getLocalizedMessage();
75: throw new RuntimeException(msg, t);
76: }
77:
78: }
79: }
80:
81: }
|