Debian Codegraph @

src/com/adobe/internal/xmp/impl/XMPSerializerRDF.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.impl;
11
12 import java.io.IOException;
13 import java.io.OutputStream;
14 import java.io.OutputStreamWriter;
15 import java.util.Arrays;
16 import java.util.HashSet;
17 import java.util.Iterator;
18 import java.util.Set;
19
20 import com.adobe.internal.xmp.XMPConst;
21 import com.adobe.internal.xmp.XMPError;
22 import com.adobe.internal.xmp.XMPException;
23 import com.adobe.internal.xmp.XMPMeta;
24 import com.adobe.internal.xmp.XMPMetaFactory;
25 import com.adobe.internal.xmp.options.SerializeOptions;
26
27
28 /**
29 * Serializes the <code>XMPMeta</code>-object using the standard RDF serialization format.
30 * The output is written to an <code>OutputStream</code>
31 * according to the <code>SerializeOptions</code>.
32 * FfF: Move to XMLStreamWriter (a lot of test would break due to slight format change).
33 *
34 * @author Stefan Makswit
35 * @version $Revision$
36 * @since 11.07.2006
37 */
38 public class XMPSerializerRDF
39 {
40 /** default padding */
41 private static final int DEFAULT_PAD = 2048;
42 /** */
43 private static final String PACKET_HEADER =
44 "<?xpacket begin=\"\uFEFF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>";
45 /** The w/r is missing inbetween */
46 private static final String PACKET_TRAILER = "<?xpacket end=\"";
47 /** */
48 private static final String PACKET_TRAILER2 = "\"?>";
49 /** */
50 private static final String RDF_XMPMETA_START =
51 "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"";
52 /** */
53 private static final String RDF_XMPMETA_END = "</x:xmpmeta>";
54 /** */
55 private static final String RDF_RDF_START =
56 "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">";
57 /** */
58 private static final String RDF_RDF_END = "</rdf:RDF>";
59
60 /** */
61 private static final String RDF_SCHEMA_START = "<rdf:Description rdf:about=";
62 /** */
63 private static final String RDF_SCHEMA_END = "</rdf:Description>";
64 /** */
65 private static final String RDF_STRUCT_START = "<rdf:Description";
66 /** */
67 private static final String RDF_STRUCT_END = "</rdf:Description>";
68 /** */
69 private static final String RDF_EMPTY_STRUCT = "<rdf:Description/>";
70 /** a set of all rdf attribute qualifier */
71 static final Set RDF_ATTR_QUALIFIER = new HashSet(Arrays.asList(new String[] {
72 XMPConst.XML_LANG, "rdf:resource", "rdf:ID", "rdf:bagID", "rdf:nodeID" }));
73
74 /** the metadata object to be serialized. */
75 private XMPMetaImpl xmp;
76 /** the output stream to serialize to */
77 private CountOutputStream outputStream;
78 /** this writer is used to do the actual serialization */
79 private OutputStreamWriter writer;
80 /** the stored serialization options */
81 private SerializeOptions options;
82 /** the size of one unicode char, for UTF-8 set to 1
83 * (Note: only valid for ASCII chars lower than 0x80),
84 * set to 2 in case of UTF-16 */
85 private int unicodeSize = 1; // UTF-8
86 /** the padding in the XMP Packet, or the length of the complete packet in
87 * case of option <em>exactPacketLength</em>. */
88 private int padding;
89
90
91 /**
92 * The actual serialization.
93 *
94 * @param xmp the metadata object to be serialized
95 * @param out outputStream the output stream to serialize to
96 * @param options the serialization options
97 *
98 * @throws XMPException If case of wrong options or any other serialization error.
99 */
100 public void serialize(XMPMeta xmp, OutputStream out,
101 SerializeOptions options) throws XMPException
102 {
103 try
104 {
105 outputStream = new CountOutputStream(out);
106 writer = new OutputStreamWriter(outputStream, options.getEncoding());
107
108 this.xmp = (XMPMetaImpl) xmp;
109 this.options = options;
110 this.padding = options.getPadding();
111
112 writer = new OutputStreamWriter(outputStream, options.getEncoding());
113
114 checkOptionsConsistence();
115
116 // serializes the whole packet, but don't write the tail yet
117 // and flush to make sure that the written bytes are calculated correctly
118 String tailStr = serializeAsRDF();
119 writer.flush();
120
121 // adds padding
122 addPadding(tailStr.length());
123
124 // writes the tail
125 write(tailStr);
126 writer.flush();
127
128 outputStream.close();
129 }
130 catch (IOException e)
131 {
132 throw new XMPException("Error writing to the OutputStream", XMPError.UNKNOWN);
133 }
134 }
135
136
137 /**
138 * Calculates the padding according to the options and write it to the stream.
139 * @param tailLength the length of the tail string
140 * @throws XMPException thrown if packet size is to small to fit the padding
141 * @throws IOException forwards writer errors
142 */
143 private void addPadding(int tailLength) throws XMPException, IOException
144 {
145 if (options.getExactPacketLength())
146 {
147 // the string length is equal to the length of the UTF-8 encoding
148 int minSize = outputStream.getBytesWritten() + tailLength * unicodeSize;
149 if (minSize > padding)
150 {
151 throw new XMPException("Can't fit into specified packet size",
152 XMPError.BADSERIALIZE);
153 }
154 padding -= minSize; // Now the actual amount of padding to add.
155 }
156
157 // fix rest of the padding according to Unicode unit size.
158 padding /= unicodeSize;
159
160 int newlineLen = options.getNewline().length();
161 if (padding >= newlineLen)
162 {
163 padding -= newlineLen; // Write this newline last.
164 while (padding >= (100 + newlineLen))
165 {
166 writeChars(100, ' ');
167 writeNewline();
168 padding -= (100 + newlineLen);
169 }
170 writeChars(padding, ' ');
171 writeNewline();
172 }
173 else
174 {
175 writeChars(padding, ' ');
176 }
177 }
178
179
180 /**
181 * Checks if the supplied options are consistent.
182 * @throws XMPException Thrown if options are conflicting
183 */
184 protected void checkOptionsConsistence() throws XMPException
185 {
186 if (options.getEncodeUTF16BE() | options.getEncodeUTF16LE())
187 {
188 unicodeSize = 2;
189 }
190
191 if (options.getExactPacketLength())
192 {
193 if (options.getOmitPacketWrapper() | options.getIncludeThumbnailPad())
194 {
195 throw new XMPException("Inconsistent options for exact size serialize",
196 XMPError.BADOPTIONS);
197 }
198 if ((options.getPadding() & (unicodeSize - 1)) != 0)
199 {
200 throw new XMPException("Exact size must be a multiple of the Unicode element",
201 XMPError.BADOPTIONS);
202 }
203 }
204 else if (options.getReadOnlyPacket())
205 {
206 if (options.getOmitPacketWrapper() | options.getIncludeThumbnailPad())
207 {
208 throw new XMPException("Inconsistent options for read-only packet",
209 XMPError.BADOPTIONS);
210 }
211 padding = 0;
212 }
213 else if (options.getOmitPacketWrapper())
214 {
215 if (options.getIncludeThumbnailPad())
216 {
217 throw new XMPException("Inconsistent options for non-packet serialize",
218 XMPError.BADOPTIONS);
219 }
220 padding = 0;
221 }
222 else
223 {
224 if (padding == 0)
225 {
226 padding = DEFAULT_PAD * unicodeSize;
227 }
228
229 if (options.getIncludeThumbnailPad())
230 {
231 if (!xmp.doesPropertyExist(XMPConst.NS_XMP, "Thumbnails"))
232 {
233 padding += 10000 * unicodeSize;
234 }
235 }
236 }
237 }
238
239
240 /**
241 * Writes the (optional) packet header and the outer rdf-tags.
242 * @return Returns the packet end processing instraction to be written after the padding.
243 * @throws IOException Forwarded writer exceptions.
244 * @throws XMPException
245 */
246 private String serializeAsRDF() throws IOException, XMPException
247 {
248 int level = 0;
249
250 // Write the packet header PI.
251 if (!options.getOmitPacketWrapper())
252 {
253 writeIndent(level);
254 write(PACKET_HEADER);
255 writeNewline();
256 }
257
258 // Write the x:xmpmeta element's start tag.
259 if (!options.getOmitXmpMetaElement())
260 {
261 writeIndent(level);
262 write(RDF_XMPMETA_START);
263 // Note: this flag can only be set by unit tests
264 if (!options.getOmitVersionAttribute())
265 {
266 write(XMPMetaFactory.getVersionInfo().getMessage());
267 }
268 write("\">");
269 writeNewline();
270 level++;
271 }
272
273 // Write the rdf:RDF start tag.
274 writeIndent(level);
275 write(RDF_RDF_START);
276 writeNewline();
277
278 // Write all of the properties.
279 if (options.getUseCanonicalFormat())
280 {
281 serializeCanonicalRDFSchemas(level);
282 }
283 else
284 {
285 serializeCompactRDFSchemas(level);
286 }
287
288 // Write the rdf:RDF end tag.
289 writeIndent(level);
290 write(RDF_RDF_END);
291 writeNewline();
292
293 // Write the xmpmeta end tag.
294 if (!options.getOmitXmpMetaElement())
295 {
296 level--;
297 writeIndent(level);
298 write(RDF_XMPMETA_END);
299 writeNewline();
300 }
301 // Write the packet trailer PI into the tail string as UTF-8.
302 String tailStr = "";
303 if (!options.getOmitPacketWrapper())
304 {
305 for (level = options.getBaseIndent(); level > 0; level--)
306 {
307 tailStr += options.getIndent();
308 }
309
310 tailStr += PACKET_TRAILER;
311 tailStr += options.getReadOnlyPacket() ? 'r' : 'w';
312 tailStr += PACKET_TRAILER2;
313 }
314
315 return tailStr;
316 }
317
318
319 /**
320 * Serializes the metadata in pretty-printed manner.
321 * @param level indent level
322 * @throws IOException Forwarded writer exceptions
323 * @throws XMPException
324 */
325 private void serializeCanonicalRDFSchemas(int level) throws IOException, XMPException
326 {
327 if (xmp.getRoot().getChildrenLength() > 0)
328 {
329 startOuterRDFDescription(xmp.getRoot(), level);
330
331 for (Iterator it = xmp.getRoot().iterateChildren(); it.hasNext(); )
332 {
333 XMPNode currSchema = (XMPNode) it.next();
334 serializeCanonicalRDFSchema(currSchema, level);
335 }
336
337 endOuterRDFDescription(level);
338 }
339 else
340 {
341 writeIndent(level + 1);
342 write(RDF_SCHEMA_START); // Special case an empty XMP object.
343 writeTreeName();
344 write("/>");
345 writeNewline();
346 }
347 }
348
349
350 /**
351 * @throws IOException
352 */
353 private void writeTreeName() throws IOException
354 {
355 write('"');
356 String name = xmp.getRoot().getName();
357 if (name != null)
358 {
359 appendNodeValue(name, true);
360 }
361 write('"');
362 }
363
364
365 /**
366 * Serializes the metadata in compact manner.
367 * @param level indent level to start with
368 * @throws IOException Forwarded writer exceptions
369 * @throws XMPException
370 */
371 private void serializeCompactRDFSchemas(int level) throws IOException, XMPException
372 {
373 // Begin the rdf:Description start tag.
374 writeIndent(level + 1);
375 write(RDF_SCHEMA_START);
376 writeTreeName();
377
378 // Write all necessary xmlns attributes.
379 Set usedPrefixes = new HashSet();
380 usedPrefixes.add("xml");
381 usedPrefixes.add("rdf");
382
383 for (Iterator it = xmp.getRoot().iterateChildren(); it.hasNext();)
384 {
385 XMPNode schema = (XMPNode) it.next();
386 declareUsedNamespaces(schema, usedPrefixes, level + 3);
387 }
388
389 // Write the top level "attrProps" and close the rdf:Description start tag.
390 boolean allAreAttrs = true;
391 for (Iterator it = xmp.getRoot().iterateChildren(); it.hasNext();)
392 {
393 XMPNode schema = (XMPNode) it.next();
394 allAreAttrs &= serializeCompactRDFAttrProps (schema, level + 2);
395 }
396
397 if (!allAreAttrs)
398 {
399 write('>');
400 writeNewline();
401 }
402 else
403 {
404 write("/>");
405 writeNewline();
406 return; // ! Done if all properties in all schema are written as attributes.
407 }
408
409 // Write the remaining properties for each schema.
410 for (Iterator it = xmp.getRoot().iterateChildren(); it.hasNext();)
411 {
412 XMPNode schema = (XMPNode) it.next();
413 serializeCompactRDFElementProps (schema, level + 2);
414 }
415
416 // Write the rdf:Description end tag.
417 // *** Elide the end tag if everything (all props in all schema) is an attr.
418 writeIndent(level + 1);
419 write(RDF_SCHEMA_END);
420 writeNewline();
421 }
422
423
424
425 /**
426 * Write each of the parent's simple unqualified properties as an attribute. Returns true if all
427 * of the properties are written as attributes.
428 *
429 * @param parentNode the parent property node
430 * @param indent the current indent level
431 * @return Returns true if all properties can be rendered as RDF attribute.
432 * @throws IOException
433 */
434 private boolean serializeCompactRDFAttrProps(XMPNode parentNode, int indent) throws IOException
435 {
436 boolean allAreAttrs = true;
437
438 for (Iterator it = parentNode.iterateChildren(); it.hasNext();)
439 {
440 XMPNode prop = (XMPNode) it.next();
441
442 if (canBeRDFAttrProp(prop))
443 {
444 writeNewline();
445 writeIndent(indent);
446 write(prop.getName());
447 write("=\"");
448 appendNodeValue(prop.getValue(), true);
449 write('"');
450 }
451 else
452 {
453 allAreAttrs = false;
454 }
455 }
456 return allAreAttrs;
457 }
458
459
460 /**
461 * Recursively handles the "value" for a node that must be written as an RDF
462 * property element. It does not matter if it is a top level property, a
463 * field of a struct, or an item of an array. The indent is that for the
464 * property element. The patterns bwlow ignore attribute qualifiers such as
465 * xml:lang, they don't affect the output form.
466 *
467 * <blockquote>
468 *
469 * <pre>
470 * &lt;ns:UnqualifiedStructProperty-1
471 * ... The fields as attributes, if all are simple and unqualified
472 * /&gt;
473 *
474 * &lt;ns:UnqualifiedStructProperty-2 rdf:parseType=&quot;Resource&quot;&gt;
475 * ... The fields as elements, if none are simple and unqualified
476 * &lt;/ns:UnqualifiedStructProperty-2&gt;
477 *
478 * &lt;ns:UnqualifiedStructProperty-3&gt;
479 * &lt;rdf:Description
480 * ... The simple and unqualified fields as attributes
481 * &gt;
482 * ... The compound or qualified fields as elements
483 * &lt;/rdf:Description&gt;
484 * &lt;/ns:UnqualifiedStructProperty-3&gt;
485 *
486 * &lt;ns:UnqualifiedArrayProperty&gt;
487 * &lt;rdf:Bag&gt; or Seq or Alt
488 * ... Array items as rdf:li elements, same forms as top level properties
489 * &lt;/rdf:Bag&gt;
490 * &lt;/ns:UnqualifiedArrayProperty&gt;
491 *
492 * &lt;ns:QualifiedProperty rdf:parseType=&quot;Resource&quot;&gt;
493 * &lt;rdf:value&gt; ... Property &quot;value&quot;
494 * following the unqualified forms ... &lt;/rdf:value&gt;
495 * ... Qualifiers looking like named struct fields
496 * &lt;/ns:QualifiedProperty&gt;
497 * </pre>
498 *
499 * </blockquote>
500 *
501 * *** Consider numbered array items, but has compatibility problems. ***
502 * Consider qualified form with rdf:Description and attributes.
503 *
504 * @param parentNode the parent node
505 * @param indent the current indent level
506 * @throws IOException Forwards writer exceptions
507 * @throws XMPException If qualifier and element fields are mixed.
508 */
509 private void serializeCompactRDFElementProps(XMPNode parentNode, int indent)
510 throws IOException, XMPException
511 {
512 for (Iterator it = parentNode.iterateChildren(); it.hasNext();)
513 {
514 XMPNode node = (XMPNode) it.next();
515 if (canBeRDFAttrProp (node))
516 {
517 continue;
518 }
519
520 boolean emitEndTag = true;
521 boolean indentEndTag = true;
522
523 // Determine the XML element name, write the name part of the start tag. Look over the
524 // qualifiers to decide on "normal" versus "rdf:value" form. Emit the attribute
525 // qualifiers at the same time.
526 String elemName = node.getName();
527 if (XMPConst.ARRAY_ITEM_NAME.equals(elemName))
528 {
529 elemName = "rdf:li";
530 }
531
532 writeIndent(indent);
533 write('<');
534 write(elemName);
535
536 boolean hasGeneralQualifiers = false;
537 boolean hasRDFResourceQual = false;
538
539 for (Iterator iq = node.iterateQualifier(); iq.hasNext();)
540 {
541 XMPNode qualifier = (XMPNode) iq.next();
542 if (!RDF_ATTR_QUALIFIER.contains(qualifier.getName()))
543 {
544 hasGeneralQualifiers = true;
545 }
546 else
547 {
548 hasRDFResourceQual = "rdf:resource".equals(qualifier.getName());
549 write(' ');
550 write(qualifier.getName());
551 write("=\"");
552 appendNodeValue(qualifier.getValue(), true);
553 write('"');
554 }
555 }
556
557
558 // Process the property according to the standard patterns.
559 if (hasGeneralQualifiers)
560 {
561 serializeCompactRDFGeneralQualifier(indent, node);
562 }
563 else
564 {
565 // This node has only attribute qualifiers. Emit as a property element.
566 if (!node.getOptions().isCompositeProperty())
567 {
568 Object[] result = serializeCompactRDFSimpleProp(node);
569 emitEndTag = ((Boolean) result[0]).booleanValue();
570 indentEndTag = ((Boolean) result[1]).booleanValue();
571 }
572 else if (node.getOptions().isArray())
573 {
574 serializeCompactRDFArrayProp(node, indent);
575 }
576 else
577 {
578 emitEndTag = serializeCompactRDFStructProp(
579 node, indent, hasRDFResourceQual);
580 }
581
582 }
583
584 // Emit the property element end tag.
585 if (emitEndTag)
586 {
587 if (indentEndTag)
588 {
589 writeIndent(indent);
590 }
591 write("</");
592 write(elemName);
593 write('>');
594 writeNewline();
595 }
596
597 }
598 }
599
600
601 /**
602 * Serializes a simple property.
603 *
604 * @param node an XMPNode
605 * @return Returns an array containing the flags emitEndTag and indentEndTag.
606 * @throws IOException Forwards the writer exceptions.
607 */
608 private Object[] serializeCompactRDFSimpleProp(XMPNode node) throws IOException
609 {
610 // This is a simple property.
611 Boolean emitEndTag = Boolean.TRUE;
612 Boolean indentEndTag = Boolean.TRUE;
613
614 if (node.getOptions().isURI())
615 {
616 write(" rdf:resource=\"");
617 appendNodeValue(node.getValue(), true);
618 write("\"/>");
619 writeNewline();
620 emitEndTag = Boolean.FALSE;
621 }
622 else if (node.getValue() == null || node.getValue().length() == 0)
623 {
624 write("/>");
625 writeNewline();
626 emitEndTag = Boolean.FALSE;
627 }
628 else
629 {
630 write('>');
631 appendNodeValue (node.getValue(), false);
632 indentEndTag = Boolean.FALSE;
633 }
634
635 return new Object[] {emitEndTag, indentEndTag};
636 }
637
638
639 /**
640 * Serializes an array property.
641 *
642 * @param node an XMPNode
643 * @param indent the current indent level
644 * @throws IOException Forwards the writer exceptions.
645 * @throws XMPException If qualifier and element fields are mixed.
646 */
647 private void serializeCompactRDFArrayProp(XMPNode node, int indent) throws IOException,
648 XMPException
649 {
650 // This is an array.
651 write('>');
652 writeNewline();
653 emitRDFArrayTag (node, true, indent + 1);
654
655 if (node.getOptions().isArrayAltText())
656 {
657 XMPNodeUtils.normalizeLangArray (node);
658 }
659
660 serializeCompactRDFElementProps(node, indent + 2);
661
662 emitRDFArrayTag(node, false, indent + 1);
663 }
664
665
666 /**
667 * Serializes a struct property.
668 *
669 * @param node an XMPNode
670 * @param indent the current indent level
671 * @param hasRDFResourceQual Flag if the element has resource qualifier
672 * @return Returns true if an end flag shall be emitted.
673 * @throws IOException Forwards the writer exceptions.
674 * @throws XMPException If qualifier and element fields are mixed.
675 */
676 private boolean serializeCompactRDFStructProp(XMPNode node, int indent,
677 boolean hasRDFResourceQual) throws XMPException, IOException
678 {
679 // This must be a struct.
680 boolean hasAttrFields = false;
681 boolean hasElemFields = false;
682 boolean emitEndTag = true;
683
684 for (Iterator ic = node.iterateChildren(); ic.hasNext(); )
685 {
686 XMPNode field = (XMPNode) ic.next();
687 if (canBeRDFAttrProp(field))
688 {
689 hasAttrFields = true;
690 }
691 else
692 {
693 hasElemFields = true;
694 }
695
696 if (hasAttrFields && hasElemFields)
697 {
698 break; // No sense looking further.
699 }
700 }
701
702 if (hasRDFResourceQual && hasElemFields)
703 {
704 throw new XMPException(
705 "Can't mix rdf:resource qualifier and element fields",
706 XMPError.BADRDF);
707 }
708
709 if (!node.hasChildren())
710 {
711 // Catch an empty struct as a special case. The case
712 // below would emit an empty
713 // XML element, which gets reparsed as a simple property
714 // with an empty value.
715 write(" rdf:parseType=\"Resource\"/>");
716 writeNewline();
717 emitEndTag = false;
718
719 }
720 else if (!hasElemFields)
721 {
722 // All fields can be attributes, use the
723 // emptyPropertyElt form.
724 serializeCompactRDFAttrProps(node, indent + 1);
725 write("/>");
726 writeNewline();
727 emitEndTag = false;
728
729 }
730 else if (!hasAttrFields)
731 {
732 // All fields must be elements, use the
733 // parseTypeResourcePropertyElt form.
734 write(" rdf:parseType=\"Resource\">");
735 writeNewline();
736 serializeCompactRDFElementProps(node, indent + 1);
737
738 }
739 else
740 {
741 // Have a mix of attributes and elements, use an inner rdf:Description.
742 write('>');
743 writeNewline();
744 writeIndent(indent + 1);
745 write(RDF_STRUCT_START);
746 serializeCompactRDFAttrProps(node, indent + 2);
747 write(">");
748 writeNewline();
749 serializeCompactRDFElementProps(node, indent + 1);
750 writeIndent(indent + 1);
751 write(RDF_STRUCT_END);
752 writeNewline();
753 }
754 return emitEndTag;
755 }
756
757
758 /**
759 * Serializes the general qualifier.
760 * @param node the root node of the subtree
761 * @param indent the current indent level
762 * @throws IOException Forwards all writer exceptions.
763 * @throws XMPException If qualifier and element fields are mixed.
764 */
765 private void serializeCompactRDFGeneralQualifier(int indent, XMPNode node)
766 throws IOException, XMPException
767 {
768 // The node has general qualifiers, ones that can't be
769 // attributes on a property element.
770 // Emit using the qualified property pseudo-struct form. The
771 // value is output by a call
772 // to SerializePrettyRDFProperty with emitAsRDFValue set.
773
774 // *** We're losing compactness in the calls to SerializePrettyRDFProperty.
775 // *** Should refactor to have SerializeCompactRDFProperty that does one node.
776 write(" rdf:parseType=\"Resource\">");
777 writeNewline();
778
779 serializeCanonicalRDFProperty(node, false, true, indent + 1);
780
781 for (Iterator iq = node.iterateQualifier(); iq.hasNext();)
782 {
783 XMPNode qualifier = (XMPNode) iq.next();
784 serializeCanonicalRDFProperty(qualifier, false, false, indent + 1);
785 }
786 }
787
788
789 /**
790 * Serializes one schema with all contained properties in pretty-printed
791 * manner.<br>
792 * Each schema's properties are written to a single
793 * rdf:Description element. All of the necessary namespaces are declared in
794 * the rdf:Description element. The baseIndent is the base level for the
795 * entire serialization, that of the x:xmpmeta element. An xml:lang
796 * qualifier is written as an attribute of the property start tag, not by
797 * itself forcing the qualified property form.
798 *
799 * <blockquote>
800 *
801 * <pre>
802 * &lt;rdf:Description rdf:about=&quot;TreeName&quot; xmlns:ns=&quot;URI&quot; ... &gt;
803 *
804 * ... The actual properties of the schema, see SerializePrettyRDFProperty
805 *
806 * &lt;!-- ns1:Alias is aliased to ns2:Actual --&gt; ... If alias comments are wanted
807 *
808 * &lt;/rdf:Description&gt;
809 * </pre>
810 *
811 * </blockquote>
812 *
813 * @param schemaNode a schema node
814 * @param level
815 * @throws IOException Forwarded writer exceptions
816 * @throws XMPException
817 */
818 private void serializeCanonicalRDFSchema(XMPNode schemaNode, int level) throws IOException, XMPException
819 {
820 // Write each of the schema's actual properties.
821 for (Iterator it = schemaNode.iterateChildren(); it.hasNext();)
822 {
823 XMPNode propNode = (XMPNode) it.next();
824 serializeCanonicalRDFProperty(propNode, options.getUseCanonicalFormat(), false, level + 2);
825 }
826 }
827
828
829 /**
830 * Writes all used namespaces of the subtree in node to the output.
831 * The subtree is recursivly traversed.
832 * @param node the root node of the subtree
833 * @param usedPrefixes a set containing currently used prefixes
834 * @param indent the current indent level
835 * @throws IOException Forwards all writer exceptions.
836 */
837 private void declareUsedNamespaces(XMPNode node, Set usedPrefixes, int indent)
838 throws IOException
839 {
840 if (node.getOptions().isSchemaNode())
841 {
842 // The schema node name is the URI, the value is the prefix.
843 String prefix = node.getValue().substring(0, node.getValue().length() - 1);
844 declareNamespace(prefix, node.getName(), usedPrefixes, indent);
845 }
846 else if (node.getOptions().isStruct())
847 {
848 for (Iterator it = node.iterateChildren(); it.hasNext();)
849 {
850 XMPNode field = (XMPNode) it.next();
851 declareNamespace(field.getName(), null, usedPrefixes, indent);
852 }
853 }
854
855 for (Iterator it = node.iterateChildren(); it.hasNext();)
856 {
857 XMPNode child = (XMPNode) it.next();
858 declareUsedNamespaces(child, usedPrefixes, indent);
859 }
860
861 for (Iterator it = node.iterateQualifier(); it.hasNext();)
862 {
863 XMPNode qualifier = (XMPNode) it.next();
864 declareNamespace(qualifier.getName(), null, usedPrefixes, indent);
865 declareUsedNamespaces(qualifier, usedPrefixes, indent);
866 }
867 }
868
869
870 /**
871 * Writes one namespace declaration to the output.
872 * @param prefix a namespace prefix (without colon) or a complete qname (when namespace == null)
873 * @param namespace the a namespace
874 * @param usedPrefixes a set containing currently used prefixes
875 * @param indent the current indent level
876 * @throws IOException Forwards all writer exceptions.
877 */
878 private void declareNamespace(String prefix, String namespace, Set usedPrefixes, int indent)
879 throws IOException
880 {
881 if (namespace == null)
882 {
883 // prefix contains qname, extract prefix and lookup namespace with prefix
884 QName qname = new QName(prefix);
885 if (qname.hasPrefix())
886 {
887 prefix = qname.getPrefix();
888 // add colon for lookup
889 namespace = XMPMetaFactory.getSchemaRegistry().getNamespaceURI(prefix + ":");
890 // prefix w/o colon
891 declareNamespace(prefix, namespace, usedPrefixes, indent);
892 }
893 else
894 {
895 return;
896 }
897 }
898
899 if (!usedPrefixes.contains(prefix))
900 {
901 writeNewline();
902 writeIndent(indent);
903 write("xmlns:");
904 write(prefix);
905 write("=\"");
906 write(namespace);
907 write('"');
908 usedPrefixes.add(prefix);
909 }
910 }
911
912
913 /**
914 * Start the outer rdf:Description element, including all needed xmlns attributes.
915 * Leave the element open so that the compact form can add property attributes.
916 *
917 * @throws IOException If the writing to
918 */
919 private void startOuterRDFDescription(XMPNode schemaNode, int level) throws IOException
920 {
921 writeIndent(level + 1);
922 write(RDF_SCHEMA_START);
923 writeTreeName();
924
925 Set usedPrefixes = new HashSet();
926 usedPrefixes.add("xml");
927 usedPrefixes.add("rdf");
928
929 declareUsedNamespaces(schemaNode, usedPrefixes, level + 3);
930
931 write('>');
932 writeNewline();
933 }
934
935
936 /**
937 * Write the </rdf:Description> end tag.
938 */
939 private void endOuterRDFDescription(int level) throws IOException
940 {
941 writeIndent(level + 1);
942 write(RDF_SCHEMA_END);
943 writeNewline();
944 }
945
946
947 /**
948 * Recursively handles the "value" for a node. It does not matter if it is a
949 * top level property, a field of a struct, or an item of an array. The
950 * indent is that for the property element. An xml:lang qualifier is written
951 * as an attribute of the property start tag, not by itself forcing the
952 * qualified property form. The patterns below mostly ignore attribute
953 * qualifiers like xml:lang. Except for the one struct case, attribute
954 * qualifiers don't affect the output form.
955 *
956 * <blockquote>
957 *
958 * <pre>
959 * &lt;ns:UnqualifiedSimpleProperty&gt;value&lt;/ns:UnqualifiedSimpleProperty&gt;
960 *
961 * &lt;ns:UnqualifiedStructProperty&gt; (If no rdf:resource qualifier)
962 * &lt;rdf:Description&gt;
963 * ... Fields, same forms as top level properties
964 * &lt;/rdf:Description&gt;
965 * &lt;/ns:UnqualifiedStructProperty&gt;
966 *
967 * &lt;ns:ResourceStructProperty rdf:resource=&quot;URI&quot;
968 * ... Fields as attributes
969 * &gt;
970 *
971 * &lt;ns:UnqualifiedArrayProperty&gt;
972 * &lt;rdf:Bag&gt; or Seq or Alt
973 * ... Array items as rdf:li elements, same forms as top level properties
974 * &lt;/rdf:Bag&gt;
975 * &lt;/ns:UnqualifiedArrayProperty&gt;
976 *
977 * &lt;ns:QualifiedProperty&gt;
978 * &lt;rdf:Description&gt;
979 * &lt;rdf:value&gt; ... Property &quot;value&quot; following the unqualified
980 * forms ... &lt;/rdf:value&gt;
981 * ... Qualifiers looking like named struct fields
982 * &lt;/rdf:Description&gt;
983 * &lt;/ns:QualifiedProperty&gt;
984 * </pre>
985 *
986 * </blockquote>
987 *
988 * @param node the property node
989 * @param emitAsRDFValue property shall be rendered as attribute rather than tag
990 * @param useCanonicalRDF use canonical form with inner description tag or
991 * the compact form with rdf:ParseType=&quot;resource&quot; attribute.
992 * @param indent the current indent level
993 * @throws IOException Forwards all writer exceptions.
994 * @throws XMPException If &quot;rdf:resource&quot; and general qualifiers are mixed.
995 */
996 private void serializeCanonicalRDFProperty(
997 XMPNode node, boolean useCanonicalRDF, boolean emitAsRDFValue, int indent)
998 throws IOException, XMPException
999 {
1000 boolean emitEndTag = true;
1001 boolean indentEndTag = true;
1002
1003 // Determine the XML element name. Open the start tag with the name and
1004 // attribute qualifiers.
1005
1006 String elemName = node.getName();
1007 if (emitAsRDFValue)
1008 {
1009 elemName = "rdf:value";
1010 }
1011 else if (XMPConst.ARRAY_ITEM_NAME.equals(elemName))
1012 {
1013 elemName = "rdf:li";
1014 }
1015
1016 writeIndent(indent);
1017 write('<');
1018 write(elemName);
1019
1020 boolean hasGeneralQualifiers = false;
1021 boolean hasRDFResourceQual = false;
1022
1023 for (Iterator it = node.iterateQualifier(); it.hasNext();)
1024 {
1025 XMPNode qualifier = (XMPNode) it.next();
1026 if (!RDF_ATTR_QUALIFIER.contains(qualifier.getName()))
1027 {
1028 hasGeneralQualifiers = true;
1029 }
1030 else
1031 {
1032 hasRDFResourceQual = "rdf:resource".equals(qualifier.getName());
1033 if (!emitAsRDFValue)
1034 {
1035 write(' ');
1036 write(qualifier.getName());
1037 write("=\"");
1038 appendNodeValue(qualifier.getValue(), true);
1039 write('"');
1040 }
1041 }
1042 }
1043
1044 // Process the property according to the standard patterns.
1045
1046 if (hasGeneralQualifiers && !emitAsRDFValue)
1047 {
1048 // This node has general, non-attribute, qualifiers. Emit using the
1049 // qualified property form.
1050 // ! The value is output by a recursive call ON THE SAME NODE with
1051 // emitAsRDFValue set.
1052
1053 if (hasRDFResourceQual)
1054 {
1055 throw new XMPException("Can't mix rdf:resource and general qualifiers",
1056 XMPError.BADRDF);
1057 }
1058
1059 // Change serialization to canonical format with inner rdf:Description-tag
1060 // depending on option
1061 if (useCanonicalRDF)
1062 {
1063 write(">");
1064 writeNewline();
1065
1066 indent++;
1067 writeIndent(indent);
1068 write(RDF_STRUCT_START);
1069 write(">");
1070 }
1071 else
1072 {
1073 write(" rdf:parseType=\"Resource\">");
1074 }
1075 writeNewline();
1076
1077 serializeCanonicalRDFProperty(node, useCanonicalRDF, true, indent + 1);
1078
1079 for (Iterator it = node.iterateQualifier(); it.hasNext();)
1080 {
1081 XMPNode qualifier = (XMPNode) it.next();
1082 if (!RDF_ATTR_QUALIFIER.contains(qualifier.getName()))
1083 {
1084 serializeCanonicalRDFProperty(qualifier, useCanonicalRDF, false, indent + 1);
1085 }
1086 }
1087
1088 if (useCanonicalRDF)
1089 {
1090 writeIndent(indent);
1091 write(RDF_STRUCT_END);
1092 writeNewline();
1093 indent--;
1094 }
1095 }
1096 else
1097 {
1098 // This node has no general qualifiers. Emit using an unqualified form.
1099
1100 if (!node.getOptions().isCompositeProperty())
1101 {
1102 // This is a simple property.
1103
1104 if (node.getOptions().isURI())
1105 {
1106 write(" rdf:resource=\"");
1107 appendNodeValue(node.getValue(), true);
1108 write("\"/>");
1109 writeNewline();
1110 emitEndTag = false;
1111 }
1112 else if (node.getValue() == null || "".equals(node.getValue()))
1113 {
1114 write("/>");
1115 writeNewline();
1116 emitEndTag = false;
1117 }
1118 else
1119 {
1120 write('>');
1121 appendNodeValue(node.getValue(), false);
1122 indentEndTag = false;
1123 }
1124 }
1125 else if (node.getOptions().isArray())
1126 {
1127 // This is an array.
1128 write('>');
1129 writeNewline();
1130 emitRDFArrayTag(node, true, indent + 1);
1131 if (node.getOptions().isArrayAltText())
1132 {
1133 XMPNodeUtils.normalizeLangArray(node);
1134 }
1135 for (Iterator it = node.iterateChildren(); it.hasNext();)
1136 {
1137 XMPNode child = (XMPNode) it.next();
1138 serializeCanonicalRDFProperty(child, useCanonicalRDF, false, indent + 2);
1139 }
1140 emitRDFArrayTag(node, false, indent + 1);
1141
1142
1143 }
1144 else if (!hasRDFResourceQual)
1145 {
1146 // This is a "normal" struct, use the rdf:parseType="Resource" form.
1147 if (!node.hasChildren())
1148 {
1149 // Change serialization to canonical format with inner rdf:Description-tag
1150 // if option is set
1151 if (useCanonicalRDF)
1152 {
1153 write(">");
1154 writeNewline();
1155 writeIndent(indent + 1);
1156 write(RDF_EMPTY_STRUCT);
1157 }
1158 else
1159 {
1160 write(" rdf:parseType=\"Resource\"/>");
1161 emitEndTag = false;
1162 }
1163 writeNewline();
1164 }
1165 else
1166 {
1167 // Change serialization to canonical format with inner rdf:Description-tag
1168 // if option is set
1169 if (useCanonicalRDF)
1170 {
1171 write(">");
1172 writeNewline();
1173 indent++;
1174 writeIndent(indent);
1175 write(RDF_STRUCT_START);
1176 write(">");
1177 }
1178 else
1179 {
1180 write(" rdf:parseType=\"Resource\">");
1181 }
1182 writeNewline();
1183
1184 for (Iterator it = node.iterateChildren(); it.hasNext();)
1185 {
1186 XMPNode child = (XMPNode) it.next();
1187 serializeCanonicalRDFProperty(child, useCanonicalRDF, false, indent + 1);
1188 }
1189
1190 if (useCanonicalRDF)
1191 {
1192 writeIndent(indent);
1193 write(RDF_STRUCT_END);
1194 writeNewline();
1195 indent--;
1196 }
1197 }
1198 }
1199 else
1200 {
1201 // This is a struct with an rdf:resource attribute, use the
1202 // "empty property element" form.
1203 for (Iterator it = node.iterateChildren(); it.hasNext();)
1204 {
1205 XMPNode child = (XMPNode) it.next();
1206 if (!canBeRDFAttrProp(child))
1207 {
1208 throw new XMPException("Can't mix rdf:resource and complex fields",
1209 XMPError.BADRDF);
1210 }
1211 writeNewline();
1212 writeIndent(indent + 1);
1213 write(' ');
1214 write(child.getName());
1215 write("=\"");
1216 appendNodeValue(child.getValue(), true);
1217 write('"');
1218 }
1219 write("/>");
1220 writeNewline();
1221 emitEndTag = false;
1222 }
1223 }
1224
1225 // Emit the property element end tag.
1226 if (emitEndTag)
1227 {
1228 if (indentEndTag)
1229 {
1230 writeIndent(indent);
1231 }
1232 write("</");
1233 write(elemName);
1234 write('>');
1235 writeNewline();
1236 }
1237 }
1238
1239
1240 /**
1241 * Writes the array start and end tags.
1242 *
1243 * @param arrayNode an array node
1244 * @param isStartTag flag if its the start or end tag
1245 * @param indent the current indent level
1246 * @throws IOException forwards writer exceptions
1247 */
1248 private void emitRDFArrayTag(XMPNode arrayNode, boolean isStartTag, int indent)
1249 throws IOException
1250 {
1251 if (isStartTag || arrayNode.hasChildren())
1252 {
1253 writeIndent(indent);
1254 write(isStartTag ? "<rdf:" : "</rdf:");
1255
1256 if (arrayNode.getOptions().isArrayAlternate())
1257 {
1258 write("Alt");
1259 }
1260 else if (arrayNode.getOptions().isArrayOrdered())
1261 {
1262 write("Seq");
1263 }
1264 else
1265 {
1266 write("Bag");
1267 }
1268
1269 if (isStartTag && !arrayNode.hasChildren())
1270 {
1271 write("/>");
1272 }
1273 else
1274 {
1275 write(">");
1276 }
1277
1278 writeNewline();
1279 }
1280 }
1281
1282
1283 /**
1284 * Serializes the node value in XML encoding. Its used for tag bodies and
1285 * attributes. <em>Note:</em> The attribute is always limited by quotes,
1286 * thats why <code>&amp;apos;</code> is never serialized. <em>Note:</em>
1287 * Control chars are written unescaped, but if the user uses others than tab, LF
1288 * and CR the resulting XML will become invalid.
1289 *
1290 * @param value the value of the node
1291 * @param forAttribute flag if value is an attribute value
1292 * @throws IOException
1293 */
1294 private void appendNodeValue(String value, boolean forAttribute) throws IOException
1295 {
1296 if (value == null)
1297 {
1298 value = "";
1299 }
1300 write (Utils.escapeXML(value, forAttribute, true));
1301 }
1302
1303
1304 /**
1305 * A node can be serialized as RDF-Attribute, if it meets the following conditions:
1306 * <ul>
1307 * <li>is not array item
1308 * <li>don't has qualifier
1309 * <li>is no URI
1310 * <li>is no composite property
1311 * </ul>
1312 *
1313 * @param node an XMPNode
1314 * @return Returns true if the node serialized as RDF-Attribute
1315 */
1316 private boolean canBeRDFAttrProp(XMPNode node)
1317 {
1318 // FfF: other possibilities than []? if ( propNode->name[0] == '[' ) return false;
1319 return
1320 !node.hasQualifier() &&
1321 !node.getOptions().isURI() &&
1322 !node.getOptions().isCompositeProperty() &&
1323 !XMPConst.ARRAY_ITEM_NAME.equals(node.getName());
1324 }
1325
1326
1327 /**
1328 * Writes indents and automatically includes the baseindend from the options.
1329 * @param times number of indents to write
1330 * @throws IOException forwards exception
1331 */
1332 private void writeIndent(int times) throws IOException
1333 {
1334 for (int i = options.getBaseIndent() + times; i > 0; i--)
1335 {
1336 writer.write(options.getIndent());
1337 }
1338 }
1339
1340
1341 /**
1342 * Writes a char to the output.
1343 * @param c a char
1344 * @throws IOException forwards writer exceptions
1345 */
1346 private void write(int c) throws IOException
1347 {
1348 writer.write(c);
1349 }
1350
1351
1352 /**
1353 * Writes a String to the output.
1354 * @param str a String
1355 * @throws IOException forwards writer exceptions
1356 */
1357 private void write(String str) throws IOException
1358 {
1359 writer.write(str);
1360 }
1361
1362
1363 /**
1364 * Writes an amount of chars, mostly spaces
1365 * @param number number of chars
1366 * @param c a char
1367 * @throws IOException
1368 */
1369 private void writeChars(int number, char c) throws IOException
1370 {
1371 for (; number > 0; number--)
1372 {
1373 writer.write(c);
1374 }
1375 }
1376
1377
1378 /**
1379 * Writes a newline according to the options.
1380 * @throws IOException Forwards exception
1381 */
1382 private void writeNewline() throws IOException
1383 {
1384 writer.write(options.getNewline());
1385 }
1386 }