Debian Codegraph @

net/sf/saxon/serialize/CDATAFilter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.serialize;
9
10 import net.sf.saxon.event.ProxyReceiver;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.event.ReceiverOptions;
13 import net.sf.saxon.expr.parser.ExplicitLocation;
14 import net.sf.saxon.expr.parser.Location;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.om.FingerprintedQName;
17 import net.sf.saxon.om.NodeName;
18 import net.sf.saxon.om.StructuredQName;
19 import net.sf.saxon.serialize.charcode.CharacterSet;
20 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.tree.tiny.CharSlice;
23 import net.sf.saxon.tree.util.FastStringBuffer;
24 import net.sf.saxon.type.SchemaType;
25
26 import javax.xml.transform.OutputKeys;
27 import java.util.*;
28
29 /**
30 * CDATAFilter: This ProxyEmitter converts character data to CDATA sections,
31 * if the character data belongs to one of a set of element types to be handled this way.
32 *
33 * @author Michael Kay
34 */
35
36
37 public class CDATAFilter extends ProxyReceiver {
38
39 private FastStringBuffer buffer = new FastStringBuffer(FastStringBuffer.C256);
40 private Stack<NodeName> stack = new Stack<NodeName>();
41 private Set<NodeName> nameList; // names of cdata elements
42 private CharacterSet characterSet;
43
44 /**
45 * Create a CDATA Filter
46 *
47 * @param next the next receiver in the pipeline
48 */
49
50 public CDATAFilter(Receiver next) {
51 super(next);
52 }
53
54 /**
55 * Set the properties for this CDATA filter
56 *
57 * @param details the output properties
58 * @throws net.sf.saxon.trans.XPathException
59 * if an error occurs
60 */
61
62 public void setOutputProperties(/*@NotNull*/ Properties details)
63 throws XPathException {
64 getCdataElements(details);
65 characterSet = getConfiguration().getCharacterSetFactory().getCharacterSet(details);
66 }
67
68 /**
69 * Output element start tag
70 */
71
72 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
73 flush();
74 stack.push(elemName);
75 nextReceiver.startElement(elemName, typeCode, location, properties);
76 }
77
78 /**
79 * Output element end tag
80 */
81
82 public void endElement() throws XPathException {
83 flush();
84 stack.pop();
85 nextReceiver.endElement();
86 }
87
88 /**
89 * Output a processing instruction
90 */
91
92 public void processingInstruction(String target, CharSequence data, Location locationId, int properties) throws XPathException {
93 flush();
94 nextReceiver.processingInstruction(target, data, locationId, properties);
95 }
96
97 /**
98 * Output character data
99 */
100
101 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
102
103 if ((properties & ReceiverOptions.DISABLE_ESCAPING) == 0) {
104 buffer.append(chars.toString());
105 } else {
106 // if the user requests disable-output-escaping, this overrides the CDATA request. We end
107 // the CDATA section and output the characters as supplied.
108 flush();
109 nextReceiver.characters(chars, locationId, properties);
110 }
111 }
112
113 /**
114 * Output a comment
115 */
116
117 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
118 flush();
119 nextReceiver.comment(chars, locationId, properties);
120 }
121
122
123 /**
124 * Flush the buffer containing accumulated character data,
125 * generating it as CDATA where appropriate
126 */
127
128 private void flush() throws XPathException {
129 boolean cdata;
130 int end = buffer.length();
131 if (end == 0) {
132 return;
133 }
134
135 if (stack.isEmpty()) {
136 cdata = false; // text is not part of any element
137 } else {
138 NodeName top = stack.peek();
139 cdata = isCDATA(top);
140 }
141
142 if (cdata) {
143
144 // Check that the buffer doesn't include a character not available in the current
145 // encoding
146
147 int start = 0;
148 int k = 0;
149 while (k < end) {
150 int next = buffer.charAt(k);
151 int skip = 1;
152 if (UTF16CharacterSet.isHighSurrogate((char) next)) {
153 next = UTF16CharacterSet.combinePair((char) next, buffer.charAt(k + 1));
154 skip = 2;
155 }
156 if (next != 0 && characterSet.inCharset(next)) {
157 k++;
158 } else {
159
160 // flush out the preceding characters as CDATA
161
162 char[] array = new char[k - start];
163 buffer.getChars(start, k, array, 0);
164 flushCDATA(array, k - start);
165
166 while (k < end) {
167 // output consecutive non-encodable characters
168 // before restarting the CDATA section
169 //super.characters(CharBuffer.wrap(buffer, k, k+skip), 0, 0);
170 nextReceiver.characters(buffer.subSequence(k, k + skip),
171 ExplicitLocation.UNKNOWN_LOCATION, ReceiverOptions.DISABLE_CHARACTER_MAPS);
172 // was: (..., ReceiverOptions.DISABLE_ESCAPING);
173 k += skip;
174 if (k >= end) {
175 break;
176 }
177 next = buffer.charAt(k);
178 skip = 1;
179 if (UTF16CharacterSet.isHighSurrogate((char) next)) {
180 next = UTF16CharacterSet.combinePair((char) next, buffer.charAt(k + 1));
181 skip = 2;
182 }
183 if (characterSet.inCharset(next)) {
184 break;
185 }
186 }
187 start = k;
188 }
189 }
190 char[] rest = new char[end - start];
191 buffer.getChars(start, end, rest, 0);
192 flushCDATA(rest, end - start);
193
194 } else {
195 nextReceiver.characters(buffer, ExplicitLocation.UNKNOWN_LOCATION, 0);
196 }
197
198 buffer.setLength(0);
199
200 }
201
202 /**
203 * Output an array as a CDATA section. At this stage we have checked that all the characters
204 * are OK, but we haven't checked that there is no "]]>" sequence in the data
205 *
206 * @param array the data to be output
207 * @param len the number of characters in the array actually used
208 */
209
210 private void flushCDATA(char[] array, int len) throws XPathException {
211 if (len == 0) {
212 return;
213 }
214 final int chprop = ReceiverOptions.DISABLE_ESCAPING | ReceiverOptions.DISABLE_CHARACTER_MAPS;
215 final Location loc = ExplicitLocation.UNKNOWN_LOCATION;
216 nextReceiver.characters("<![CDATA[", loc, chprop);
217
218 // Check that the character data doesn't include the substring "]]>"
219 // Also get rid of any zero bytes inserted by character map expansion
220
221 int i = 0;
222 int doneto = 0;
223 while (i < len - 2) {
224 if (array[i] == ']' && array[i + 1] == ']' && array[i + 2] == '>') {
225 nextReceiver.characters(new CharSlice(array, doneto, i + 2 - doneto), loc, chprop);
226 nextReceiver.characters("]]><![CDATA[", loc, chprop);
227 doneto = i + 2;
228 } else if (array[i] == 0) {
229 nextReceiver.characters(new CharSlice(array, doneto, i - doneto), loc, chprop);
230 doneto = i + 1;
231 }
232 i++;
233 }
234 nextReceiver.characters(new CharSlice(array, doneto, len - doneto), loc, chprop);
235 nextReceiver.characters("]]>", loc, chprop);
236 }
237
238
239 /**
240 * See if a particular element is a CDATA element. Method is protected to allow
241 * overriding in a subclass.
242 *
243 * @param elementName identifies the name of element we are interested
244 * @return true if this element is included in cdata-section-elements
245 */
246
247 protected boolean isCDATA(NodeName elementName) {
248 return nameList.contains(elementName);
249 }
250
251 /**
252 * Extract the list of CDATA elements from the output properties
253 *
254 * @param details the output properties
255 */
256
257 private void getCdataElements(Properties details) {
258 boolean isHTML = "html".equals(details.getProperty(OutputKeys.METHOD));
259 boolean isHTML5 = isHTML && "5.0".equals(details.getProperty(OutputKeys.VERSION));
260 boolean isHTML4 = isHTML && !isHTML5;
261 String cdata = details.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
262 if (cdata == null) {
263 // this doesn't happen, but there's no harm allowing for it
264 nameList = new HashSet<NodeName>(0);
265 return;
266 }
267 nameList = new HashSet<NodeName>(10);
268 StringTokenizer st2 = new StringTokenizer(cdata, " \t\n\r", false);
269 while (st2.hasMoreTokens()) {
270 String expandedName = st2.nextToken();
271 StructuredQName sq = StructuredQName.fromClarkName(expandedName);
272 String uri = sq.getURI();
273 if (!isHTML || (isHTML4 && !uri.equals("")) || (isHTML5 && !uri.equals("") && !uri.equals(NamespaceConstant.XHTML))) {
274 nameList.add(new FingerprintedQName("", sq.getURI(), sq.getLocalPart()));
275 }
276 }
277 }
278
279 }
280