1 package org.jmage.filterchain;
2
3 import org.apache.log4j.Logger;
4 import org.apache.log4j.Priority;
5 import org.jmage.filter.ConfigurableImageFilter;
6 import org.jmage.filter.ImageFilter;
7 import org.jmage.util.XmlUtil;
8 import org.w3c.dom.Document;
9 import org.w3c.dom.Node;
10
11 import javax.xml.parsers.DocumentBuilder;
12 import javax.xml.parsers.DocumentBuilderFactory;
13 import javax.xml.parsers.ParserConfigurationException;
14 import java.util.Enumeration;
15 import java.util.Iterator;
16 import java.util.Properties;
17
18 /***
19 * Serializes a FilterChain to an xml dom Document.
20 */
21 public class XmlFilterChainSerializer {
22 protected Document serialized;
23
24 protected static Logger log = Logger.getLogger(XmlFilterChainSerializer.class.getName());
25 private static XmlUtil xmlUtil = new XmlUtil();
26 private static final String NAME = "name";
27 private static final String FILTERCHAIN = "filterchain";
28 private static final String FILTER = "filter";
29 private static final String PROPERTY = "property";
30 private static final String VALUE = "value";
31
32 public XmlFilterChainSerializer() {
33 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
34 DocumentBuilder builder = null;
35 try {
36 builder = factory.newDocumentBuilder();
37 } catch (ParserConfigurationException e) {
38 String message = "unable to build xml DocumentBuilderFactory, please" +
39 "check your xml parser settings";
40 assert (false) : message;
41 if (log.isEnabledFor(Priority.ERROR)) log.error(message);
42 }
43 serialized = builder.newDocument();
44 }
45
46 public Document serialize(FilterChain filterChain) {
47
48 Node filterChainNode = (Node) serialized.appendChild(serialized.createElement(FILTERCHAIN));
49 xmlUtil.setAttribute(filterChainNode, NAME, filterChain.getName());
50
51
52 Iterator it = filterChain.filters.iterator();
53 while (it.hasNext()) {
54 ImageFilter filter = (ImageFilter) it.next();
55 this.serialize(filter, filterChainNode);
56 }
57
58 return serialized;
59 }
60
61 private void serialize(ImageFilter filter, Node parent) {
62 Node filterNode = parent.appendChild(serialized.createElement(FILTER));
63 xmlUtil.setAttribute(filterNode, NAME, filter.getClass().getName());
64
65 if (filter instanceof ConfigurableImageFilter) {
66 Properties props = ((ConfigurableImageFilter) filter).getFilterProperties();
67 Enumeration paramNames = props.propertyNames();
68 while (paramNames.hasMoreElements()) {
69 String propKey = (String) paramNames.nextElement();
70 String value = props.getProperty(propKey);
71 Node propertyNode = serialized.createElement(PROPERTY);
72 xmlUtil.setAttribute(propertyNode, NAME, propKey);
73 xmlUtil.setAttribute(propertyNode, VALUE, value);
74 filterNode.appendChild(propertyNode);
75 }
76 }
77 }
78 }