Debian Codegraph @

src/com/adobe/internal/xmp/utils/XMLStreamWriterImpl.java

raw symbols SCIP
1 // =================================================================================================
2 // ADOBE SYSTEMS INCORPORATED
3 // Copyright 2006 Adobe Systems Incorporated
4 // All Rights Reserved
5 //
6 // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
7 // of the Adobe license agreement accompanying it.
8 // =================================================================================================
9
10 package com.adobe.internal.xmp.utils;
11
12 import java.io.IOException;
13 import java.io.Writer;
14 import java.util.HashSet;
15 import java.util.Stack;
16
17 import com.adobe.internal.xmp.impl.Utils;
18 import com.adobe.internal.xmp.options.SerializeOptions;
19
20
21 /**
22 * Uncomplete implementation of XMPStreamWriter of the upcoming XML Streaming API,
23 * that is adapted to be used for XMPCore.
24 * Adds automatically correct closing of empty tags > and pretty printing.
25 * Simplifies namespace handling; just tracks if a certain prefix has already been registered.
26 * FfF: If StAX will become part of the JRE, it might be replaced.
27 *
28 * @author Stefan Makswit
29 * @version $Revision$
30 * @since 09.11.2006
31 */
32 public class XMLStreamWriterImpl
33 {
34 /** */
35 private static final String DEFAULTNS = "";
36 /** */
37 private Writer writer;
38 /** */
39 private boolean startElementOpened = false;
40 /** */
41 private boolean emptyElement = false;
42 /** these two stacks are used to implement the writeEndElement() method */
43 private Stack qNameStack = new Stack();
44
45 /** */
46 private char[] newLineStr = new char[] { '\r' };
47 /** */
48 private int baseIndent = 0;
49 /** */
50 private char[] indentStr = new char[] { ' ', ' ' };
51 /** */
52 private int indentLevel = 0;
53 /** Flag if chars enclosed in a tag are indented like body tags. */
54 private boolean charIndent = false;
55 /** flag if namespaces should start in a new line */
56 private boolean namespaceLF = true;
57
58 /** internal flag tracking the linefeeds */
59 private boolean preventWhitespace = false;
60 /** internal flag tracking the linefeeds */
61 private boolean preventNextLF = true;
62 /** stores the already registiered namspaces */
63 private final HashSet registeredPrefixes = new HashSet();
64 /** whitespaces (linefeeds) shall be escaped */
65 private boolean escapeWhitespaces = true;
66
67
68 /**
69 * Default constructor providing a writer the XML is written to
70 * and the serializsation options to determine indents, whitespaces and lineendings.
71 *
72 * @param writer a <code>Writer</code>
73 * @param options the serialization options
74 */
75 public XMLStreamWriterImpl(Writer writer, SerializeOptions options)
76 {
77 this(writer);
78 this.newLineStr = options.getNewline().toCharArray();
79 this.indentStr = options.getIndent().toCharArray();
80 this.baseIndent = options.getBaseIndent();
81 }
82
83
84 /**
85 * Default constructor providing a writer the XML is written to.
86 * @param writer a <code>Writer</code>
87 */
88 public XMLStreamWriterImpl(Writer writer)
89 {
90 this.writer = writer;
91 }
92
93
94 /**
95 * Writes a start tag.
96 * @param qname a QName
97 * @throws IOException If an I/O error occurs
98 */
99
100 public void writeStartElement(String qname) throws IOException
101 {
102 if (qname == null)
103 {
104 throw new IllegalArgumentException("The element name may not be null");
105 }
106
107 closeStartElement();
108
109 writeNewLine();
110 write("<");
111 write(qname);
112 startElementOpened = true;
113 this.qNameStack.push(qname);
114 }
115
116
117 /**
118 * Differs from writeStartElement in that writeEndElement needs and must not be called.
119 * @param qname a QName
120 * @throws IOException If an I/O error occurs
121 */
122 public void writeEmptyElement(String qname) throws IOException
123 {
124 writeStartElement(qname);
125 emptyElement = true;
126 }
127
128
129 /**
130 * Writes a closing tag if the tag in scope has body elements or &gt; if its
131 * empty.
132 *
133 * @throws IOException If an I/O error occurs
134 */
135 public void writeEndElement() throws IOException
136 {
137 if (startElementOpened)
138 {
139 qNameStack.pop();
140 write("/>");
141 startElementOpened = false;
142
143 if (emptyElement)
144 {
145 writeCloseElement();
146 emptyElement = false;
147 }
148 }
149 else
150 {
151 writeCloseElement();
152 }
153 }
154
155
156 /**
157 * Closes the writer.
158 * @throws IOException If an I/O error occurs
159 */
160 public void close() throws IOException
161 {
162 flush();
163 writer.close();
164 }
165
166
167 /**
168 * Calls flush() on the writer.
169 * @throws IOException If an I/O error occurs
170 */
171 public void flush() throws IOException
172 {
173 this.writer.flush();
174 }
175
176
177 /**
178 * Completes the document by writing the end tags for all open tags.
179 * @throws IOException If an I/O error occurs
180 */
181 public void writeEndDocument() throws IOException
182 {
183 while (!this.qNameStack.isEmpty())
184 {
185 writeEndElement();
186 }
187 }
188
189
190 /**
191 * Writes an attribute into an open tag.
192 * @param qname a QName
193 * @param value the attribute value
194 * @throws IOException If an I/O error occurs
195 */
196 public void writeAttribute(String qname, String value) throws IOException
197 {
198 if (!this.startElementOpened)
199 {
200 throw new IOException("A start element must be written before an attribute");
201 }
202 // prepareNamespace(namespaceURI);
203 write(" ");
204 write(qname);
205 write("=\"");
206 writeCharactersInternal(value.toCharArray(), 0, value.length(), true);
207 write("\"");
208 }
209
210
211 /**
212 * Writes a namespace attribute and tracks if the namespace is already defined.
213 * @param prefix the namespace prefix.
214 * @param namespaceURI the namespace URI
215 * @throws IOException If an I/O error occurs
216 */
217 public void writeNamespace(String prefix, String namespaceURI) throws IOException
218 {
219 if (!this.startElementOpened)
220 {
221 throw new IOException("A start element must be written before a namespace");
222 }
223 if (prefix == null || "".equals(prefix) || "xmlns".equals(prefix))
224 {
225 writeDefaultNamespace(namespaceURI);
226 return;
227 }
228 if (needToWriteNamespace(prefix))
229 {
230 if (namespaceLF)
231 {
232 indentLevel++;
233 writeNewLine();
234 indentLevel--;
235 }
236 else
237 {
238 write(' ');
239 }
240 write("xmlns:");
241 write(prefix);
242 write("=\"");
243 write(namespaceURI);
244 write("\"");
245 }
246 }
247
248
249 /**
250 * Writes the default namespace
251 * @param namespaceURI the default namespace
252 * @throws IOException If an I/O error occurs
253 */
254 public void writeDefaultNamespace(String namespaceURI) throws IOException
255 {
256 if (!this.startElementOpened)
257 {
258 throw new IOException("A start element must be written before the default namespace");
259 }
260 if (needToWriteNamespace(DEFAULTNS))
261 {
262 write(" xmlns");
263 write("=\"");
264 write(namespaceURI);
265 write("\"");
266 // setPrefix(DEFAULTNS, namespaceURI);
267 }
268 }
269
270
271 /**
272 * Writes a comment.
273 * @param comment the comment to write
274 * @throws IOException If an I/O error occurs
275 */
276 public void writeComment(String comment) throws IOException
277 {
278 closeStartElement();
279 write("<!--");
280 if (comment != null)
281 {
282 write(comment);
283 }
284 write("-->");
285 }
286
287
288 /**
289 * Writes a processing instruction.
290 * @param target a target
291 * @throws IOException If an I/O error occurs
292 */
293 public void writeProcessingInstruction(String target) throws IOException
294 {
295 closeStartElement();
296 writeProcessingInstruction(target, null);
297 }
298
299
300 /**
301 * Writes a processing instruction.
302 * @param target a target
303 * @param text the instruction text
304 * @throws IOException If an I/O error occurs
305 */
306 public void writeProcessingInstruction(String target, String text) throws IOException
307 {
308 closeStartElement();
309 writeNewLine();
310 write("<?");
311 if (target != null)
312 { // isn't passing null an error, actually?
313 write(target);
314 }
315 if (text != null)
316 {
317 // Need a separating white space
318 write(' ');
319 write(text);
320 }
321 write("?>");
322 }
323
324
325 /**
326 * Writes the DTD.
327 * @param dtd the dtd to write
328 * @throws IOException If an I/O error occurs
329 */
330 public void writeDTD(String dtd) throws IOException
331 {
332 writeNewLine();
333 write(dtd);
334 }
335
336
337 /**
338 * Writes CData.
339 * @param data the data to write
340 * @throws IOException If an I/O error occurs
341 */
342 public void writeCData(String data) throws IOException
343 {
344 closeStartElement();
345 write("<![CDATA[");
346 if (data != null)
347 {
348 write(data);
349 }
350 write("]]>");
351 }
352
353
354 /**
355 * Writes an entity reference.
356 * @param name the name of the reference
357 * @throws IOException If an I/O error occurs
358 */
359 public void writeEntityRef(String name) throws IOException
360 {
361 closeStartElement();
362 write("&");
363 write(name);
364 write(";");
365 }
366
367
368 /**
369 * Writes the XML-header and version.
370 * @throws IOException If an I/O error occurs
371 */
372 public void writeStartDocument() throws IOException
373 {
374 writeNewLine();
375 write("<?xml version='1.0' encoding='utf-8'?>");
376 }
377
378
379 /**
380 * Writes the XML-header and version.
381 * @param version th xml-version
382 * @throws IOException If an I/O error occurs
383 */
384 public void writeStartDocument(String version) throws IOException
385 {
386 writeNewLine();
387 write("<?xml version='");
388 write(version);
389 write("'?>");
390 }
391
392
393 /**
394 * Writes the XML-header, encoding and version.
395 * @param encoding the file encoding
396 * @param version th XML-version
397 * @throws IOException If an I/O error occurs
398 */
399 public void writeStartDocument(String encoding, String version) throws IOException
400 {
401 writeNewLine();
402 write("<?xml version='");
403 write(version);
404 write("' encoding='");
405 write(encoding);
406 write("'?>");
407 }
408
409
410 /**
411 * Writes XML-characters.
412 * @param text xml characters
413 * @throws IOException If an I/O error occurs
414 */
415 public void writeCharacters(String text) throws IOException
416 {
417 writeCharacters(text.toCharArray(), 0, text.length());
418 }
419
420
421 /**
422 * Writes a part of a char array.
423 * @param buffer a character array
424 * @param off the offset within the array
425 * @param length the amount of character to write
426 * @throws IOException If an I/O error occurs
427 */
428 public void writeCharacters(char[] buffer, int off, int length) throws IOException
429 {
430 boolean openStartElement = startElementOpened;
431 closeStartElement();
432
433 if (openStartElement)
434 {
435 if (charIndent)
436 {
437 writeNewLine();
438 }
439 else
440 {
441 preventWhitespace = true;
442 }
443 }
444
445 writeCharactersInternal(buffer, off, length, false);
446 }
447
448
449 /**
450 * @param escapeWhitespaces the escapeWhitespaces to set
451 */
452 public void setEscapeWhitespaces(boolean escapeWhitespaces)
453 {
454 this.escapeWhitespaces = escapeWhitespaces;
455 }
456
457
458 /**
459 * Writes a string.
460 * @param str a String
461 * @throws IOException If an I/O error occurs
462 */
463 private void write(String str) throws IOException
464 {
465 this.writer.write(str);
466 }
467
468
469 /**
470 * Writes a char
471 * @param ch a char
472 * @throws IOException
473 */
474 private void write(char ch) throws IOException
475 {
476 this.writer.write(ch);
477 }
478
479
480 /**
481 * Writes a char array.
482 * @param buffer a char array
483 * @throws IOException
484 */
485 private void write(char[] buffer) throws IOException
486 {
487 this.writer.write(buffer);
488 }
489
490
491 /**
492 * Writes XML characters to the writer.
493 * @param buffer a character array
494 * @param off the offset
495 * @param length the amount of characters to write
496 * @param isAttributeValue flag if it is an attribute value (needed for escaping)
497 * @throws IOException
498 */
499 private void writeCharactersInternal(char[] buffer, int off, int length,
500 boolean isAttributeValue) throws IOException
501 {
502 indentLevel++;
503
504 String value = Utils.escapeXML(new String(buffer, off, length),
505 isAttributeValue, escapeWhitespaces);
506 writer.write(value);
507
508 indentLevel--;
509 }
510
511
512 /**
513 * Closes an open tag, either with an end tag or with "/>".
514 * @throws IOException
515 */
516 private void closeStartElement() throws IOException
517 {
518 if (this.startElementOpened)
519 {
520 if (!emptyElement)
521 {
522 write(">");
523 }
524 else
525 {
526 qNameStack.pop();
527 write("/>");
528 emptyElement = false;
529 indentLevel--;
530 }
531 this.startElementOpened = false;
532 indentLevel++;
533 }
534 }
535
536
537 /**
538 * Writes a closing tag.
539 * @throws IOException
540 */
541 private void writeCloseElement() throws IOException
542 {
543 indentLevel--;
544 String qname = (String) this.qNameStack.pop();
545 writeNewLine();
546 write("</");
547 write(qname);
548 write(">");
549 preventWhitespace = false;
550 }
551
552
553 /**
554 * Writes a newline and indent for the next line.
555 * @throws IOException
556 */
557 private void writeNewLine() throws IOException
558 {
559 if (!preventNextLF && !preventWhitespace)
560 {
561 write(newLineStr);
562 }
563
564 if (!preventWhitespace)
565 {
566 for (int i = baseIndent + indentLevel; i > 0; i--)
567 {
568 writer.write(indentStr);
569 }
570 }
571
572 preventNextLF = false;
573 }
574
575
576 /**
577 * Asks if the namespace needs to be written or if it has already been defined.
578 * @param prefix a prefix
579 * @return Returns true if the namespace needs to be written.
580 */
581 private boolean needToWriteNamespace(String prefix)
582 {
583 if (!registeredPrefixes.contains(prefix))
584 {
585 registeredPrefixes.add(prefix);
586 return true;
587 }
588 else
589 {
590 return false;
591 }
592 }
593 }