Debian Codegraph @

src/com/adobe/internal/xmp/impl/XMPNodeUtils.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.util.GregorianCalendar;
13 import java.util.Iterator;
14
15 import com.adobe.internal.xmp.XMPConst;
16 import com.adobe.internal.xmp.XMPDateTime;
17 import com.adobe.internal.xmp.XMPDateTimeFactory;
18 import com.adobe.internal.xmp.XMPError;
19 import com.adobe.internal.xmp.XMPException;
20 import com.adobe.internal.xmp.XMPMetaFactory;
21 import com.adobe.internal.xmp.XMPUtils;
22 import com.adobe.internal.xmp.impl.xpath.XMPPath;
23 import com.adobe.internal.xmp.impl.xpath.XMPPathSegment;
24 import com.adobe.internal.xmp.options.AliasOptions;
25 import com.adobe.internal.xmp.options.PropertyOptions;
26
27
28 /**
29 * Utilities for <code>XMPNode</code>.
30 *
31 * @author Stefan Makswit
32 * @version $Revision$
33 * @since Aug 28, 2006
34 */
35 public class XMPNodeUtils implements XMPConst
36 {
37 /** */
38 static final int CLT_NO_VALUES = 0;
39 /** */
40 static final int CLT_SPECIFIC_MATCH = 1;
41 /** */
42 static final int CLT_SINGLE_GENERIC = 2;
43 /** */
44 static final int CLT_MULTIPLE_GENERIC = 3;
45 /** */
46 static final int CLT_XDEFAULT = 4;
47 /** */
48 static final int CLT_FIRST_ITEM = 5;
49
50
51 /**
52 * Private Constructor
53 */
54 private XMPNodeUtils()
55 {
56 // EMPTY
57 }
58
59
60 /**
61 * Find or create a schema node if <code>createNodes</code> is false and
62 *
63 * @param tree the root of the xmp tree.
64 * @param namespaceURI a namespace
65 * @param createNodes a flag indicating if the node shall be created if not found.
66 * <em>Note:</em> The namespace must be registered prior to this call.
67 *
68 * @return Returns the schema node if found, <code>null</code> otherwise.
69 * Note: If <code>createNodes</code> is <code>true</code>, it is <b>always</b>
70 * returned a valid node.
71 * @throws XMPException An exception is only thrown if an error occurred, not if a
72 * node was not found.
73 */
74 static XMPNode findSchemaNode(XMPNode tree, String namespaceURI,
75 boolean createNodes)
76 throws XMPException
77 {
78 return findSchemaNode(tree, namespaceURI, null, createNodes);
79 }
80
81
82 /**
83 * Find or create a schema node if <code>createNodes</code> is true.
84 *
85 * @param tree the root of the xmp tree.
86 * @param namespaceURI a namespace
87 * @param suggestedPrefix If a prefix is suggested, the namespace is allowed to be registered.
88 * @param createNodes a flag indicating if the node shall be created if not found.
89 * <em>Note:</em> The namespace must be registered prior to this call.
90 *
91 * @return Returns the schema node if found, <code>null</code> otherwise.
92 * Note: If <code>createNodes</code> is <code>true</code>, it is <b>always</b>
93 * returned a valid node.
94 * @throws XMPException An exception is only thrown if an error occurred, not if a
95 * node was not found.
96 */
97 static XMPNode findSchemaNode(XMPNode tree, String namespaceURI, String suggestedPrefix,
98 boolean createNodes)
99 throws XMPException
100 {
101 assert tree.getParent() == null; // make sure that its the root
102 XMPNode schemaNode = tree.findChildByName(namespaceURI);
103
104 if (schemaNode == null && createNodes)
105 {
106 schemaNode = new XMPNode(namespaceURI,
107 new PropertyOptions()
108 .setSchemaNode(true));
109 schemaNode.setImplicit(true);
110
111 // only previously registered schema namespaces are allowed in the XMP tree.
112 String prefix = XMPMetaFactory.getSchemaRegistry().getNamespacePrefix(namespaceURI);
113 if (prefix == null)
114 {
115 if (suggestedPrefix != null && suggestedPrefix.length() != 0)
116 {
117 prefix = XMPMetaFactory.getSchemaRegistry().registerNamespace(namespaceURI,
118 suggestedPrefix);
119 }
120 else
121 {
122 throw new XMPException("Unregistered schema namespace URI",
123 XMPError.BADSCHEMA);
124 }
125 }
126
127 schemaNode.setValue(prefix);
128
129 tree.addChild(schemaNode);
130 }
131
132 return schemaNode;
133 }
134
135
136 /**
137 * Find or create a child node under a given parent node. If the parent node is no
138 * Returns the found or created child node.
139 *
140 * @param parent
141 * the parent node
142 * @param childName
143 * the node name to find
144 * @param createNodes
145 * flag, if new nodes shall be created.
146 * @return Returns the found or created node or <code>null</code>.
147 * @throws XMPException Thrown if
148 */
149 static XMPNode findChildNode(XMPNode parent, String childName, boolean createNodes)
150 throws XMPException
151 {
152 if (!parent.getOptions().isSchemaNode() && !parent.getOptions().isStruct())
153 {
154 if (!parent.isImplicit())
155 {
156 throw new XMPException("Named children only allowed for schemas and structs",
157 XMPError.BADXPATH);
158 }
159 else if (parent.getOptions().isArray())
160 {
161 throw new XMPException("Named children not allowed for arrays",
162 XMPError.BADXPATH);
163 }
164 else if (createNodes)
165 {
166 parent.getOptions().setStruct(true);
167 }
168 }
169
170 XMPNode childNode = parent.findChildByName(childName);
171
172 if (childNode == null && createNodes)
173 {
174 PropertyOptions options = new PropertyOptions();
175 childNode = new XMPNode(childName, options);
176 childNode.setImplicit(true);
177 parent.addChild(childNode);
178 }
179
180 assert childNode != null || !createNodes;
181
182 return childNode;
183 }
184
185
186 /**
187 * Follow an expanded path expression to find or create a node.
188 *
189 * @param xmpTree the node to begin the search.
190 * @param xpath the complete xpath
191 * @param createNodes flag if nodes shall be created
192 * (when called by <code>setProperty()</code>)
193 * @param leafOptions the options for the created leaf nodes (only when
194 * <code>createNodes == true</code>).
195 * @return Returns the node if found or created or <code>null</code>.
196 * @throws XMPException An exception is only thrown if an error occurred,
197 * not if a node was not found.
198 */
199 static XMPNode findNode(XMPNode xmpTree, XMPPath xpath, boolean createNodes,
200 PropertyOptions leafOptions) throws XMPException
201 {
202 // check if xpath is set.
203 if (xpath == null || xpath.size() == 0)
204 {
205 throw new XMPException("Empty XMPPath", XMPError.BADXPATH);
206 }
207
208 // Root of implicitly created subtree to possible delete it later.
209 // Valid only if leaf is new.
210 XMPNode rootImplicitNode = null;
211 XMPNode currNode = null;
212
213 // resolve schema step
214 currNode = findSchemaNode(xmpTree,
215 xpath.getSegment(XMPPath.STEP_SCHEMA).getName(), createNodes);
216 if (currNode == null)
217 {
218 return null;
219 }
220 else if (currNode.isImplicit())
221 {
222 currNode.setImplicit(false); // Clear the implicit node bit.
223 rootImplicitNode = currNode; // Save the top most implicit node.
224 }
225
226
227 // Now follow the remaining steps of the original XMPPath.
228 try
229 {
230 for (int i = 1; i < xpath.size(); i++)
231 {
232 currNode = followXPathStep(currNode, xpath.getSegment(i), createNodes);
233 if (currNode == null)
234 {
235 if (createNodes)
236 {
237 // delete implicitly created nodes
238 deleteNode(rootImplicitNode);
239 }
240 return null;
241 }
242 else if (currNode.isImplicit())
243 {
244 // clear the implicit node flag
245 currNode.setImplicit(false);
246
247 // if node is an ALIAS (can be only in root step, auto-create array
248 // when the path has been resolved from a not simple alias type
249 if (i == 1 &&
250 xpath.getSegment(i).isAlias() &&
251 xpath.getSegment(i).getAliasForm() != 0)
252 {
253 currNode.getOptions().setOption(xpath.getSegment(i).getAliasForm(), true);
254 }
255 // "CheckImplicitStruct" in C++
256 else if (i < xpath.size() - 1 &&
257 xpath.getSegment(i).getKind() == XMPPath.STRUCT_FIELD_STEP &&
258 !currNode.getOptions().isCompositeProperty())
259 {
260 currNode.getOptions().setStruct(true);
261 }
262
263 if (rootImplicitNode == null)
264 {
265 rootImplicitNode = currNode; // Save the top most implicit node.
266 }
267 }
268 }
269 }
270 catch (XMPException e)
271 {
272 // if new notes have been created prior to the error, delete them
273 if (rootImplicitNode != null)
274 {
275 deleteNode(rootImplicitNode);
276 }
277 throw e;
278 }
279
280
281 if (rootImplicitNode != null)
282 {
283 // set options only if a node has been successful created
284 currNode.getOptions().mergeWith(leafOptions);
285 currNode.setOptions(currNode.getOptions());
286 }
287
288 return currNode;
289 }
290
291
292 /**
293 * Deletes the the given node and its children from its parent.
294 * Takes care about adjusting the flags.
295 * FfF: think about moving is to XMPNode... (make removeChild/Qualifier private and
296 * FfF: publish just deleteNode(XMPNode)
297 * @param node the top-most node to delete.
298 */
299 static void deleteNode(XMPNode node)
300 {
301 XMPNode parent = node.getParent();
302
303 if (node.getOptions().isQualifier())
304 {
305 // root is qualifier
306 parent.removeQualifier(node);
307 }
308 else
309 {
310 // root is NO qualifier
311 parent.removeChild(node);
312 }
313
314 // delete empty Schema nodes
315 if (!parent.hasChildren() && parent.getOptions().isSchemaNode())
316 {
317 parent.getParent().removeChild(parent);
318 }
319 }
320
321
322 /**
323 * This is setting the value of a leaf node.
324 *
325 * @param node an XMPNode
326 * @param value a value
327 */
328 static void setNodeValue(XMPNode node, Object value)
329 {
330 String strValue = serializeNodeValue(value);
331 if (!(node.getOptions().isQualifier() && XML_LANG.equals(node.getName())))
332 {
333 node.setValue(strValue);
334 }
335 else
336 {
337 node.setValue(Utils.normalizeLangValue(strValue));
338 }
339 }
340
341
342 /**
343 * Verifies the PropertyOptions for consistancy and updates them as needed.
344 * If options are <code>null</code> they are created with default values.
345 * FfF: add an kind of autofix options to PropertyOptions and remove this method!!!
346 *
347 * @param options the <code>PropertyOptions</code>
348 * @param itemValue the node value to set
349 * @return Returns the updated options.
350 * @throws XMPException If the options are not consistant.
351 */
352 static PropertyOptions verifySetOptions(PropertyOptions options, Object itemValue)
353 throws XMPException
354 {
355 // create empty and fix existing options
356 if (options == null)
357 {
358 // set default options
359 options = new PropertyOptions();
360 }
361
362 if (options.isArrayAltText())
363 {
364 options.setArrayAlternate(true);
365 }
366
367 if (options.isArrayAlternate())
368 {
369 options.setArrayOrdered(true);
370 }
371
372 if (options.isArrayOrdered())
373 {
374 options.setArray(true);
375 }
376
377 if (options.isCompositeProperty() && itemValue != null && itemValue.toString().length() > 0)
378 {
379 throw new XMPException("Structs and arrays can't have values",
380 XMPError.BADOPTIONS);
381 }
382
383 options.assertConsistency(options.getOptions());
384
385 return options;
386 }
387
388
389 /**
390 * Converts the node value to String, apply special conversions for defined
391 * types in XMP.
392 *
393 * @param value
394 * the node value to set
395 * @return Returns the String representation of the node value.
396 */
397 static String serializeNodeValue(Object value)
398 {
399 String strValue;
400 if (value == null)
401 {
402 strValue = null;
403 }
404 else if (value instanceof Boolean)
405 {
406 strValue = XMPUtils.convertFromBoolean(((Boolean) value).booleanValue());
407 }
408 else if (value instanceof Integer)
409 {
410 strValue = XMPUtils.convertFromInteger(((Integer) value).intValue());
411 }
412 else if (value instanceof Long)
413 {
414 strValue = XMPUtils.convertFromLong(((Long) value).longValue());
415 }
416 else if (value instanceof Double)
417 {
418 strValue = XMPUtils.convertFromDouble(((Double) value).doubleValue());
419 }
420 else if (value instanceof XMPDateTime)
421 {
422 strValue = XMPUtils.convertFromDate((XMPDateTime) value);
423 }
424 else if (value instanceof GregorianCalendar)
425 {
426 XMPDateTime dt = XMPDateTimeFactory.createFromCalendar((GregorianCalendar) value);
427 strValue = XMPUtils.convertFromDate(dt);
428 }
429 else if (value instanceof byte[])
430 {
431 strValue = XMPUtils.encodeBase64((byte[]) value);
432 }
433 else
434 {
435 strValue = value.toString();
436 }
437
438 return strValue != null ? Utils.removeControlChars(strValue) : null;
439 }
440
441
442 /**
443 * After processing by ExpandXPath, a step can be of these forms:
444 * <ul>
445 * <li>qualName - A top level property or struct field.
446 * <li>[index] - An element of an array.
447 * <li>[last()] - The last element of an array.
448 * <li>[qualName="value"] - An element in an array of structs, chosen by a field value.
449 * <li>[?qualName="value"] - An element in an array, chosen by a qualifier value.
450 * <li>?qualName - A general qualifier.
451 * </ul>
452 * Find the appropriate child node, resolving aliases, and optionally creating nodes.
453 *
454 * @param parentNode the node to start to start from
455 * @param nextStep the xpath segment
456 * @param createNodes
457 * @return returns the found or created XMPPath node
458 * @throws XMPException
459 */
460 private static XMPNode followXPathStep(
461 XMPNode parentNode,
462 XMPPathSegment nextStep,
463 boolean createNodes) throws XMPException
464 {
465 XMPNode nextNode = null;
466 int index = 0;
467 int stepKind = nextStep.getKind();
468
469 if (stepKind == XMPPath.STRUCT_FIELD_STEP)
470 {
471 nextNode = findChildNode(parentNode, nextStep.getName(), createNodes);
472 }
473 else if (stepKind == XMPPath.QUALIFIER_STEP)
474 {
475 nextNode = findQualifierNode(
476 parentNode, nextStep.getName().substring(1), createNodes);
477 }
478 else
479 {
480 // This is an array indexing step. First get the index, then get the node.
481
482 if (!parentNode.getOptions().isArray())
483 {
484 throw new XMPException("Indexing applied to non-array", XMPError.BADXPATH);
485 }
486
487 if (stepKind == XMPPath.ARRAY_INDEX_STEP)
488 {
489 index = findIndexedItem(parentNode, nextStep.getName(), createNodes);
490 }
491 else if (stepKind == XMPPath.ARRAY_LAST_STEP)
492 {
493 index = parentNode.getChildrenLength();
494 }
495 else if (stepKind == XMPPath.FIELD_SELECTOR_STEP)
496 {
497 String[] result = Utils.splitNameAndValue(nextStep.getName());
498 String fieldName = result[0];
499 String fieldValue = result[1];
500 index = lookupFieldSelector(parentNode, fieldName, fieldValue);
501 }
502 else if (stepKind == XMPPath.QUAL_SELECTOR_STEP)
503 {
504 String[] result = Utils.splitNameAndValue(nextStep.getName());
505 String qualName = result[0];
506 String qualValue = result[1];
507 index = lookupQualSelector(
508 parentNode, qualName, qualValue, nextStep.getAliasForm());
509 }
510 else
511 {
512 throw new XMPException("Unknown array indexing step in FollowXPathStep",
513 XMPError.INTERNALFAILURE);
514 }
515
516 if (1 <= index && index <= parentNode.getChildrenLength())
517 {
518 nextNode = parentNode.getChild(index);
519 }
520 }
521
522 return nextNode;
523 }
524
525
526 /**
527 * Find or create a qualifier node under a given parent node. Returns a pointer to the
528 * qualifier node, and optionally an iterator for the node's position in
529 * the parent's vector of qualifiers. The iterator is unchanged if no qualifier node (null)
530 * is returned.
531 * <em>Note:</em> On entry, the qualName parameter must not have the leading '?' from the
532 * XMPPath step.
533 *
534 * @param parent the parent XMPNode
535 * @param qualName the qualifier name
536 * @param createNodes flag if nodes shall be created
537 * @return Returns the qualifier node if found or created, <code>null</code> otherwise.
538 * @throws XMPException
539 */
540 private static XMPNode findQualifierNode(XMPNode parent, String qualName, boolean createNodes)
541 throws XMPException
542 {
543 assert !qualName.startsWith("?");
544
545 XMPNode qualNode = parent.findQualifierByName(qualName);
546
547 if (qualNode == null && createNodes)
548 {
549 qualNode = new XMPNode(qualName, null);
550 qualNode.setImplicit(true);
551
552 parent.addQualifier(qualNode);
553 }
554
555 return qualNode;
556 }
557
558
559 /**
560 * @param arrayNode an array node
561 * @param segment the segment containing the array index
562 * @param createNodes flag if new nodes are allowed to be created.
563 * @return Returns the index or index = -1 if not found
564 * @throws XMPException Throws Exceptions
565 */
566 private static int findIndexedItem(XMPNode arrayNode, String segment, boolean createNodes)
567 throws XMPException
568 {
569 int index = 0;
570
571 try
572 {
573 segment = segment.substring(1, segment.length() - 1);
574 index = Integer.parseInt(segment);
575 if (index < 1)
576 {
577 throw new XMPException("Array index must be larger than zero",
578 XMPError.BADXPATH);
579 }
580 }
581 catch (NumberFormatException e)
582 {
583 throw new XMPException("Array index not digits.", XMPError.BADXPATH);
584 }
585
586 if (createNodes && index == arrayNode.getChildrenLength() + 1)
587 {
588 // Append a new last + 1 node.
589 XMPNode newItem = new XMPNode(ARRAY_ITEM_NAME, null);
590 newItem.setImplicit(true);
591 arrayNode.addChild(newItem);
592 }
593
594 return index;
595 }
596
597
598 /**
599 * Searches for a field selector in a node:
600 * [fieldName="value] - an element in an array of structs, chosen by a field value.
601 * No implicit nodes are created by field selectors.
602 *
603 * @param arrayNode
604 * @param fieldName
605 * @param fieldValue
606 * @return Returns the index of the field if found, otherwise -1.
607 * @throws XMPException
608 */
609 private static int lookupFieldSelector(XMPNode arrayNode, String fieldName, String fieldValue)
610 throws XMPException
611 {
612 int result = -1;
613
614 for (int index = 1; index <= arrayNode.getChildrenLength() && result < 0; index++)
615 {
616 XMPNode currItem = arrayNode.getChild(index);
617
618 if (!currItem.getOptions().isStruct())
619 {
620 throw new XMPException("Field selector must be used on array of struct",
621 XMPError.BADXPATH);
622 }
623
624 for (int f = 1; f <= currItem.getChildrenLength(); f++)
625 {
626 XMPNode currField = currItem.getChild(f);
627 if (!fieldName.equals(currField.getName()))
628 {
629 continue;
630 }
631 if (fieldValue.equals(currField.getValue()))
632 {
633 result = index;
634 break;
635 }
636 }
637 }
638
639 return result;
640 }
641
642
643 /**
644 * Searches for a qualifier selector in a node:
645 * [?qualName="value"] - an element in an array, chosen by a qualifier value.
646 * No implicit nodes are created for qualifier selectors,
647 * except for an alias to an x-default item.
648 *
649 * @param arrayNode an array node
650 * @param qualName the qualifier name
651 * @param qualValue the qualifier value
652 * @param aliasForm in case the qual selector results from an alias,
653 * an x-default node is created if there has not been one.
654 * @return Returns the index of th
655 * @throws XMPException
656 */
657 private static int lookupQualSelector(XMPNode arrayNode, String qualName,
658 String qualValue, int aliasForm) throws XMPException
659 {
660 if (XML_LANG.equals(qualName))
661 {
662 qualValue = Utils.normalizeLangValue(qualValue);
663 int index = XMPNodeUtils.lookupLanguageItem(arrayNode, qualValue);
664 if (index < 0 && (aliasForm & AliasOptions.PROP_ARRAY_ALT_TEXT) > 0)
665 {
666 XMPNode langNode = new XMPNode(ARRAY_ITEM_NAME, null);
667 XMPNode xdefault = new XMPNode(XML_LANG, X_DEFAULT, null);
668 langNode.addQualifier(xdefault);
669 arrayNode.addChild(1, langNode);
670 return 1;
671 }
672 else
673 {
674 return index;
675 }
676 }
677 else
678 {
679 for (int index = 1; index < arrayNode.getChildrenLength(); index++)
680 {
681 XMPNode currItem = arrayNode.getChild(index);
682
683 for (Iterator it = currItem.iterateQualifier(); it.hasNext();)
684 {
685 XMPNode qualifier = (XMPNode) it.next();
686 if (qualName.equals(qualifier.getName()) &&
687 qualValue.equals(qualifier.getValue()))
688 {
689 return index;
690 }
691 }
692 }
693 return -1;
694 }
695 }
696
697
698 /**
699 * Make sure the x-default item is first. Touch up &quot;single value&quot;
700 * arrays that have a default plus one real language. This case should have
701 * the same value for both items. Older Adobe apps were hardwired to only
702 * use the &quot;x-default&quot; item, so we copy that value to the other
703 * item.
704 *
705 * @param arrayNode
706 * an alt text array node
707 */
708 static void normalizeLangArray(XMPNode arrayNode)
709 {
710 if (!arrayNode.getOptions().isArrayAltText())
711 {
712 return;
713 }
714
715 // check if node with x-default qual is first place
716 for (int i = 2; i <= arrayNode.getChildrenLength(); i++)
717 {
718 XMPNode child = arrayNode.getChild(i);
719 if (child.hasQualifier() && X_DEFAULT.equals(child.getQualifier(1).getValue()))
720 {
721 // move node to first place
722 try
723 {
724 arrayNode.removeChild(i);
725 arrayNode.addChild(1, child);
726 }
727 catch (XMPException e)
728 {
729 // cannot occur, because same child is removed before
730 assert false;
731 }
732
733 if (i == 2)
734 {
735 arrayNode.getChild(2).setValue(child.getValue());
736 }
737 break;
738 }
739 }
740 }
741
742
743 /**
744 * See if an array is an alt-text array. If so, make sure the x-default item
745 * is first.
746 *
747 * @param arrayNode
748 * the array node to check if its an alt-text array
749 */
750 static void detectAltText(XMPNode arrayNode)
751 {
752 if (arrayNode.getOptions().isArrayAlternate() && arrayNode.hasChildren())
753 {
754 boolean isAltText = false;
755 for (Iterator it = arrayNode.iterateChildren(); it.hasNext();)
756 {
757 XMPNode child = (XMPNode) it.next();
758 if (child.getOptions().getHasLanguage())
759 {
760 isAltText = true;
761 break;
762 }
763 }
764
765 if (isAltText)
766 {
767 arrayNode.getOptions().setArrayAltText(true);
768 normalizeLangArray(arrayNode);
769 }
770 }
771 }
772
773
774 /**
775 * Appends a language item to an alt text array.
776 *
777 * @param arrayNode the language array
778 * @param itemLang the language of the item
779 * @param itemValue the content of the item
780 * @throws XMPException Thrown if a duplicate property is added
781 */
782 static void appendLangItem(XMPNode arrayNode, String itemLang, String itemValue)
783 throws XMPException
784 {
785 XMPNode newItem = new XMPNode(ARRAY_ITEM_NAME, itemValue, null);
786 XMPNode langQual = new XMPNode(XML_LANG, itemLang, null);
787 newItem.addQualifier(langQual);
788
789 if (!X_DEFAULT.equals(langQual.getValue()))
790 {
791 arrayNode.addChild(newItem);
792 }
793 else
794 {
795 arrayNode.addChild(1, newItem);
796 }
797 }
798
799
800 /**
801 * <ol>
802 * <li>Look for an exact match with the specific language.
803 * <li>If a generic language is given, look for partial matches.
804 * <li>Look for an "x-default"-item.
805 * <li>Choose the first item.
806 * </ol>
807 *
808 * @param arrayNode
809 * the alt text array node
810 * @param genericLang
811 * the generic language
812 * @param specificLang
813 * the specific language
814 * @return Returns the kind of match as an Integer and the found node in an
815 * array.
816 *
817 * @throws XMPException
818 */
819 static Object[] chooseLocalizedText(XMPNode arrayNode, String genericLang, String specificLang)
820 throws XMPException
821 {
822 // See if the array has the right form. Allow empty alt arrays,
823 // that is what parsing returns.
824 // *** Should check alt-text bit when that is reliably maintained.
825 if (!arrayNode.getOptions().isArrayAltText())
826 {
827 throw new XMPException("Localized text array is not alt-text", XMPError.BADXPATH);
828 }
829 else if (!arrayNode.hasChildren())
830 {
831 return new Object[] { new Integer(XMPNodeUtils.CLT_NO_VALUES), null };
832 }
833
834 int foundGenericMatches = 0;
835 XMPNode resultNode = null;
836 XMPNode xDefault = null;
837
838 // Look for the first partial match with the generic language.
839 for (Iterator it = arrayNode.iterateChildren(); it.hasNext();)
840 {
841 XMPNode currItem = (XMPNode) it.next();
842
843 // perform some checks on the current item
844 if (currItem.getOptions().isCompositeProperty())
845 {
846 throw new XMPException("Alt-text array item is not simple", XMPError.BADXPATH);
847 }
848 else if (!currItem.hasQualifier()
849 || !XML_LANG.equals(currItem.getQualifier(1).getName()))
850 {
851 throw new XMPException("Alt-text array item has no language qualifier",
852 XMPError.BADXPATH);
853 }
854
855 String currLang = currItem.getQualifier(1).getValue();
856
857 // Look for an exact match with the specific language.
858 if (specificLang.equals(currLang))
859 {
860 return new Object[] { new Integer(XMPNodeUtils.CLT_SPECIFIC_MATCH), currItem };
861 }
862 else if (genericLang != null && currLang.startsWith(genericLang))
863 {
864 if (resultNode == null)
865 {
866 resultNode = currItem;
867 }
868 // ! Don't return/break, need to look for other matches.
869 foundGenericMatches++;
870 }
871 else if (X_DEFAULT.equals(currLang))
872 {
873 xDefault = currItem;
874 }
875 }
876
877 // evaluate loop
878 if (foundGenericMatches == 1)
879 {
880 return new Object[] { new Integer(XMPNodeUtils.CLT_SINGLE_GENERIC), resultNode };
881 }
882 else if (foundGenericMatches > 1)
883 {
884 return new Object[] { new Integer(XMPNodeUtils.CLT_MULTIPLE_GENERIC), resultNode };
885 }
886 else if (xDefault != null)
887 {
888 return new Object[] { new Integer(XMPNodeUtils.CLT_XDEFAULT), xDefault };
889 }
890 else
891 {
892 // Everything failed, choose the first item.
893 return new Object[] { new Integer(XMPNodeUtils.CLT_FIRST_ITEM), arrayNode.getChild(1) };
894 }
895 }
896
897
898 /**
899 * Looks for the appropriate language item in a text alternative array.item
900 *
901 * @param arrayNode
902 * an array node
903 * @param language
904 * the requested language
905 * @return Returns the index if the language has been found, -1 otherwise.
906 * @throws XMPException
907 */
908 static int lookupLanguageItem(XMPNode arrayNode, String language) throws XMPException
909 {
910 if (!arrayNode.getOptions().isArray())
911 {
912 // *** Check for alt-text?
913 throw new XMPException("Language item must be used on array", XMPError.BADXPATH);
914 }
915
916 for (int index = 1; index <= arrayNode.getChildrenLength(); index++)
917 {
918 XMPNode child = arrayNode.getChild(index);
919 if (!child.hasQualifier() || !XML_LANG.equals(child.getQualifier(1).getName()))
920 {
921 continue;
922 }
923 else if (language.equals(child.getQualifier(1).getValue()))
924 {
925 return index;
926 }
927 }
928
929 return -1;
930 }
931 }