1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.xml;
17
18 import org.apache.commons.jelly.JellyTagException;
19 import org.apache.commons.jelly.MissingAttributeException;
20 import org.apache.commons.jelly.TagSupport;
21 import org.apache.commons.jelly.XMLOutput;
22
23 import org.xml.sax.Attributes;
24 import org.xml.sax.SAXException;
25 import org.xml.sax.helpers.AttributesImpl;
26
27 /***
28 * Replace namespace is a filter to change the namespace of any
29 * elemement attribute passing through it.
30 *
31 * @author Diogo Quintela <dquintela@gmail.com>
32 */
33 public class ReplaceNamespaceTag extends TagSupport {
34 private String fromNamespace;
35 private String toNamespace;
36
37 public ReplaceNamespaceTag() {
38 }
39
40
41
42 public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
43 final String fromURI = (fromNamespace != null) ? fromNamespace : "";
44 final String toURI = (toNamespace != null) ? toNamespace : "";
45 XMLOutput newOutput = output;
46
47 if (!toURI.equals(fromURI)) {
48 newOutput = new XMLOutput(output) {
49 public void startElement(String uri, String localName, String qName, Attributes atts)
50 throws SAXException {
51 super.startElement(replaceURI(uri), localName, qName, replaceURI(atts));
52 }
53
54 public void endElement(String uri, String localName, String qName)
55 throws SAXException {
56 super.endElement(replaceURI(uri), localName, qName);
57 }
58
59 public void startPrefixMapping(String prefix, String uri)
60 throws SAXException {
61 super.startPrefixMapping(prefix, replaceURI(uri));
62 }
63
64 private String replaceURI(String uri) {
65 String newUri = uri;
66
67 if (fromURI.equals((uri != null) ? uri : "")) {
68 newUri = toURI;
69 }
70
71 return newUri;
72 }
73
74 private Attributes replaceURI(Attributes atts) {
75 AttributesImpl newAttsImpl = new AttributesImpl();
76
77 for (int i = 0; i < atts.getLength(); i++) {
78
79
80
81 String QName = atts.getQName(i);
82 String newUri = atts.getURI(i);
83 int idx = QName.indexOf(':');
84
85 if (idx >= 0) {
86 newUri = replaceURI(newUri);
87 }
88
89 newAttsImpl.addAttribute(newUri, atts.getLocalName(i), atts.getQName(i),
90 atts.getType(i), atts.getValue(i));
91 }
92
93 return newAttsImpl;
94 }
95 };
96 }
97
98 invokeBody(newOutput);
99 }
100
101 /***
102 * @return the source namespace URI to replace
103 */
104 public String getFromURI() {
105 return fromNamespace;
106 }
107
108 /***
109 * Sets the source namespace URI to replace.
110 */
111 public void setFromURI(String namespace) {
112 this.fromNamespace = namespace;
113 }
114
115 /***
116 * @return the destination namespace URI to replace
117 */
118 public String getToURI() {
119 return toNamespace;
120 }
121
122 /***
123 * Sets the destination namespace URI to replace.
124 */
125 public void setToURI(String namespace) {
126 this.toNamespace = namespace;
127 }
128 }