Debian Codegraph @

src/com/adobe/internal/xmp/impl/XMPUtilsImpl.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
11
12 package com.adobe.internal.xmp.impl;
13
14 import java.security.MessageDigest;
15 import java.security.NoSuchAlgorithmException;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.TreeMap;
21
22 import com.adobe.internal.xmp.XMPConst;
23 import com.adobe.internal.xmp.XMPError;
24 import com.adobe.internal.xmp.XMPException;
25 import com.adobe.internal.xmp.XMPMeta;
26 import com.adobe.internal.xmp.XMPMetaFactory;
27 import com.adobe.internal.xmp.XMPSchemaRegistry;
28 import com.adobe.internal.xmp.XMPUtils;
29 import com.adobe.internal.xmp.impl.xpath.XMPPath;
30 import com.adobe.internal.xmp.impl.xpath.XMPPathParser;
31 import com.adobe.internal.xmp.options.PropertyOptions;
32 import com.adobe.internal.xmp.options.SerializeOptions;
33 import com.adobe.internal.xmp.options.TemplateOptions;
34 import com.adobe.internal.xmp.properties.XMPAliasInfo;
35
36
37
38 /**
39 * @author Stefan Makswit
40 * @version $Revision$
41 * @since 11.08.2006
42 */
43 public class XMPUtilsImpl implements XMPConst
44 {
45 /** */
46 private static final int UCK_NORMAL = 0;
47 /** */
48 private static final int UCK_SPACE = 1;
49 /** */
50 private static final int UCK_COMMA = 2;
51 /** */
52 private static final int UCK_SEMICOLON = 3;
53 /** */
54 private static final int UCK_QUOTE = 4;
55 /** */
56 private static final int UCK_CONTROL = 5;
57
58
59 /**
60 * Private constructor, as
61 */
62 private XMPUtilsImpl()
63 {
64 // EMPTY
65 }
66
67
68 /**
69 * @see XMPUtils#catenateArrayItems(XMPMeta, String, String, String, String,
70 * boolean)
71 *
72 * @param xmp
73 * The XMP object containing the array to be catenated.
74 * @param schemaNS
75 * The schema namespace URI for the array. Must not be null or
76 * the empty string.
77 * @param arrayName
78 * The name of the array. May be a general path expression, must
79 * not be null or the empty string. Each item in the array must
80 * be a simple string value.
81 * @param separator
82 * The string to be used to separate the items in the catenated
83 * string. Defaults to "; ", ASCII semicolon and space
84 * (U+003B, U+0020).
85 * @param quotes
86 * The characters to be used as quotes around array items that
87 * contain a separator. Defaults to '"'
88 * @param allowCommas
89 * Option flag to control the catenation.
90 * @return Returns the string containing the catenated array items.
91 * @throws XMPException
92 * Forwards the Exceptions from the metadata processing
93 */
94 public static String catenateArrayItems(XMPMeta xmp, String schemaNS, String arrayName,
95 String separator, String quotes, boolean allowCommas) throws XMPException
96 {
97 ParameterAsserts.assertSchemaNS(schemaNS);
98 ParameterAsserts.assertArrayName(arrayName);
99 ParameterAsserts.assertImplementation(xmp);
100 if (separator == null || separator.length() == 0)
101 {
102 separator = "; ";
103 }
104 if (quotes == null || quotes.length() == 0)
105 {
106 quotes = "\"";
107 }
108
109 XMPMetaImpl xmpImpl = (XMPMetaImpl) xmp;
110 XMPNode arrayNode = null;
111 XMPNode currItem = null;
112
113 // Return an empty result if the array does not exist,
114 // hurl if it isn't the right form.
115 XMPPath arrayPath = XMPPathParser.expandXPath(schemaNS, arrayName);
116 arrayNode = XMPNodeUtils.findNode(xmpImpl.getRoot(), arrayPath, false, null);
117 if (arrayNode == null)
118 {
119 return "";
120 }
121 else if (!arrayNode.getOptions().isArray() || arrayNode.getOptions().isArrayAlternate())
122 {
123 throw new XMPException("Named property must be non-alternate array", XMPError.BADPARAM);
124 }
125
126 // Make sure the separator is OK.
127 checkSeparator(separator);
128 // Make sure the open and close quotes are a legitimate pair.
129 char openQuote = quotes.charAt(0);
130 char closeQuote = checkQuotes(quotes, openQuote);
131
132 // Build the result, quoting the array items, adding separators.
133 // Hurl if any item isn't simple.
134
135 StringBuffer catinatedString = new StringBuffer();
136
137 for (Iterator it = arrayNode.iterateChildren(); it.hasNext();)
138 {
139 currItem = (XMPNode) it.next();
140 if (currItem.getOptions().isCompositeProperty())
141 {
142 throw new XMPException("Array items must be simple", XMPError.BADPARAM);
143 }
144 String str = applyQuotes(currItem.getValue(), openQuote, closeQuote, allowCommas);
145
146 catinatedString.append(str);
147 if (it.hasNext())
148 {
149 catinatedString.append(separator);
150 }
151 }
152
153 return catinatedString.toString();
154 }
155
156
157 /**
158 * see {@link XMPUtils#separateArrayItems(XMPMeta, String, String, String,
159 * PropertyOptions, boolean)}
160 *
161 * @param xmp
162 * The XMP object containing the array to be updated.
163 * @param schemaNS
164 * The schema namespace URI for the array. Must not be null or
165 * the empty string.
166 * @param arrayName
167 * The name of the array. May be a general path expression, must
168 * not be null or the empty string. Each item in the array must
169 * be a simple string value.
170 * @param catedStr
171 * The string to be separated into the array items.
172 * @param arrayOptions
173 * Option flags to control the separation.
174 * @param preserveCommas
175 * Flag if commas shall be preserved
176 *
177 * @throws XMPException
178 * Forwards the Exceptions from the metadata processing
179 */
180 public static void separateArrayItems(XMPMeta xmp, String schemaNS, String arrayName,
181 String catedStr, PropertyOptions arrayOptions, boolean preserveCommas)
182 throws XMPException
183 {
184
185 ParameterAsserts.assertSchemaNS(schemaNS);
186 ParameterAsserts.assertArrayName(arrayName);
187 if (catedStr == null)
188 {
189 throw new XMPException("Parameter must not be null", XMPError.BADPARAM);
190 }
191 ParameterAsserts.assertImplementation(xmp);
192 XMPMetaImpl xmpImpl = (XMPMetaImpl) xmp;
193
194 // Keep a zero value, has special meaning below.
195 XMPNode arrayNode = separateFindCreateArray(schemaNS, arrayName, arrayOptions, xmpImpl);
196
197 int arrayElementLimit = Integer.MAX_VALUE;
198 if(arrayNode != null)
199 {
200 if(arrayOptions != null)
201 {
202 arrayElementLimit = arrayOptions.getArrayElementsLimit();
203 if(arrayElementLimit == -1 )
204 {
205 arrayElementLimit = Integer.MAX_VALUE;
206 }
207 }
208 }
209 // Extract the item values one at a time, until the whole input string is done.
210 StringBuilder itemValue = new StringBuilder("");
211 int itemStart, itemEnd;
212 int nextKind = UCK_NORMAL, charKind = UCK_NORMAL;
213 char ch = 0, nextChar = 0;
214
215 itemEnd = 0;
216 int endPos = catedStr.length();
217 while (itemEnd < endPos)
218 {
219 // Skip any leading spaces and separation characters. Always skip commas here.
220 // They can be kept when within a value, but not when alone between values.
221
222 if( arrayNode.getChildrenLength() >= arrayElementLimit)
223 {
224 break;
225 }
226
227 for (itemStart = itemEnd; itemStart < endPos; itemStart++)
228 {
229 ch = catedStr.charAt(itemStart);
230 charKind = classifyCharacter(ch);
231 if (charKind == UCK_NORMAL || charKind == UCK_QUOTE)
232 {
233 break;
234 }
235 }
236 if (itemStart >= endPos)
237 {
238 break;
239 }
240
241 if (charKind != UCK_QUOTE)
242 {
243 // This is not a quoted value. Scan for the end, create an array
244 // item from the substring.
245 for (itemEnd = itemStart; itemEnd < endPos; itemEnd++)
246 {
247 ch = catedStr.charAt(itemEnd);
248 charKind = classifyCharacter(ch);
249
250 if (charKind == UCK_NORMAL || charKind == UCK_QUOTE ||
251 (charKind == UCK_COMMA && preserveCommas))
252 {
253 continue;
254 }
255 else if (charKind != UCK_SPACE)
256 {
257 break;
258 }
259 else if ((itemEnd + 1) < endPos)
260 {
261 ch = catedStr.charAt(itemEnd + 1);
262 nextKind = classifyCharacter(ch);
263 if (nextKind == UCK_NORMAL || nextKind == UCK_QUOTE ||
264 (nextKind == UCK_COMMA && preserveCommas))
265 {
266 continue;
267 }
268 }
269
270 // Anything left?
271 break; // Have multiple spaces, or a space followed by a
272 // separator.
273 }
274 itemValue = new StringBuilder(catedStr.substring(itemStart, itemEnd));
275 }
276 else
277 {
278 // Accumulate quoted values into a local string, undoubling
279 // internal quotes that
280 // match the surrounding quotes. Do not undouble "unmatching"
281 // quotes.
282
283 char openQuote = ch;
284 char closeQuote = getClosingQuote(openQuote);
285
286 itemStart++; // Skip the opening quote;
287 itemValue = new StringBuilder("");
288
289 for (itemEnd = itemStart; itemEnd < endPos; itemEnd++)
290 {
291 ch = catedStr.charAt(itemEnd);
292 charKind = classifyCharacter(ch);
293
294 if (charKind != UCK_QUOTE || !isSurroundingQuote(ch, openQuote, closeQuote))
295 {
296 // This is not a matching quote, just append it to the
297 // item value.
298 itemValue.append(ch);
299 }
300 else
301 {
302 // This is a "matching" quote. Is it doubled, or the
303 // final closing quote?
304 // Tolerate various edge cases like undoubled opening
305 // (non-closing) quotes,
306 // or end of input.
307
308 if ((itemEnd + 1) < endPos)
309 {
310 nextChar = catedStr.charAt(itemEnd + 1);
311 nextKind = classifyCharacter(nextChar);
312 }
313 else
314 {
315 nextKind = UCK_SEMICOLON;
316 nextChar = 0x3B;
317 }
318
319 if (ch == nextChar)
320 {
321 // This is doubled, copy it and skip the double.
322 itemValue.append(ch);
323 // Loop will add in charSize.
324 itemEnd++;
325 }
326 else if (!isClosingingQuote(ch, openQuote, closeQuote))
327 {
328 // This is an undoubled, non-closing quote, copy it.
329 itemValue.append(ch);
330 }
331 else
332 {
333 // This is an undoubled closing quote, skip it and
334 // exit the loop.
335 itemEnd++;
336 break;
337 }
338 }
339 }
340 }
341
342 // Add the separated item to the array.
343 // Keep a matching old value in case it had separators.
344 int foundIndex = -1;
345 for (int oldChild = 1; oldChild <= arrayNode.getChildrenLength(); oldChild++)
346 {
347 if (itemValue.toString().equals(arrayNode.getChild(oldChild).getValue()))
348 {
349 foundIndex = oldChild;
350 break;
351 }
352 }
353
354 XMPNode newItem = null;
355 if (foundIndex < 0)
356 {
357 newItem = new XMPNode(ARRAY_ITEM_NAME, itemValue.toString(), null);
358 arrayNode.addChild(newItem);
359 }
360 // <#AdobePrivate>
361 // else
362 // {
363 // newItem = arrayNode.getChild(foundIndex);
364 // // Don't match again, let duplicates be seen.
365 // arrayNode.getChild(foundIndex).setValue(null);
366 // }
367 // </#AdobePrivate>
368 }
369 }
370
371
372 /**
373 * Utility to find or create the array used by <code>separateArrayItems()</code>.
374 * @param schemaNS a the namespace fo the array
375 * @param arrayName the name of the array
376 * @param arrayOptions the options for the array if newly created
377 * @param xmp the xmp object
378 * @return Returns the array node.
379 * @throws XMPException Forwards exceptions
380 */
381 private static XMPNode separateFindCreateArray(String schemaNS, String arrayName,
382 PropertyOptions arrayOptions, XMPMetaImpl xmp) throws XMPException
383 {
384 arrayOptions = XMPNodeUtils.verifySetOptions(arrayOptions, null);
385 if (!arrayOptions.isOnlyArrayOptions())
386 {
387 throw new XMPException("Options can only provide array form", XMPError.BADOPTIONS);
388 }
389
390 // Find the array node, make sure it is OK. Move the current children
391 // aside, to be readded later if kept.
392 XMPPath arrayPath = XMPPathParser.expandXPath(schemaNS, arrayName);
393 XMPNode arrayNode = XMPNodeUtils.findNode(xmp.getRoot(), arrayPath, false, null);
394 if (arrayNode != null)
395 {
396 // The array exists, make sure the form is compatible. Zero
397 // arrayForm means take what exists.
398 PropertyOptions arrayForm = arrayNode.getOptions();
399 if (!arrayForm.isArray() || arrayForm.isArrayAlternate())
400 {
401 throw new XMPException("Named property must be non-alternate array",
402 XMPError.BADXPATH);
403 }
404 if (arrayOptions.equalArrayTypes(arrayForm))
405 {
406 throw new XMPException("Mismatch of specified and existing array form",
407 XMPError.BADXPATH); // *** Right error?
408 }
409 }
410 else
411 {
412 // The array does not exist, try to create it.
413 // don't modify the options handed into the method
414 arrayNode = XMPNodeUtils.findNode(xmp.getRoot(), arrayPath, true, arrayOptions
415 .setArray(true));
416 if (arrayNode == null)
417 {
418 throw new XMPException("Failed to create named array", XMPError.BADXPATH);
419 }
420 }
421 return arrayNode;
422 }
423
424
425 /**
426 * @see XMPUtils#removeProperties(XMPMeta, String, String, boolean, boolean)
427 *
428 * @param xmp
429 * The XMP object containing the properties to be removed.
430 *
431 * @param schemaNS
432 * Optional schema namespace URI for the properties to be
433 * removed.
434 *
435 * @param propName
436 * Optional path expression for the property to be removed.
437 *
438 * @param doAllProperties
439 * Option flag to control the deletion: do internal properties in
440 * addition to external properties.
441 * @param includeAliases
442 * Option flag to control the deletion: Include aliases in the
443 * "named schema" case above.
444 * @throws XMPException If metadata processing fails
445 */
446 public static void removeProperties(XMPMeta xmp, String schemaNS, String propName,
447 boolean doAllProperties, boolean includeAliases) throws XMPException
448 {
449 ParameterAsserts.assertImplementation(xmp);
450 XMPMetaImpl xmpImpl = (XMPMetaImpl) xmp;
451
452 if (propName != null && propName.length() > 0)
453 {
454 // Remove just the one indicated property. This might be an alias,
455 // the named schema might not actually exist. So don't lookup the
456 // schema node.
457
458 if (schemaNS == null || schemaNS.length() == 0)
459 {
460 throw new XMPException("Property name requires schema namespace",
461 XMPError.BADPARAM);
462 }
463
464 XMPPath expPath = XMPPathParser.expandXPath(schemaNS, propName);
465
466 XMPNode propNode = XMPNodeUtils.findNode(xmpImpl.getRoot(), expPath, false, null);
467 if (propNode != null)
468 {
469 if (doAllProperties
470 || !Utils.isInternalProperty(expPath.getSegment(XMPPath.STEP_SCHEMA)
471 .getName(), expPath.getSegment(XMPPath.STEP_ROOT_PROP).getName()))
472 {
473 XMPNode parent = propNode.getParent();
474 parent.removeChild(propNode);
475 if (parent.getOptions().isSchemaNode() && !parent.hasChildren())
476 {
477 // remove empty schema node
478 parent.getParent().removeChild(parent);
479 }
480
481 }
482 }
483 }
484 else if (schemaNS != null && schemaNS.length() > 0)
485 {
486
487 // Remove all properties from the named schema. Optionally include
488 // aliases, in which case
489 // there might not be an actual schema node.
490
491 // XMP_NodePtrPos schemaPos;
492 XMPNode schemaNode = XMPNodeUtils.findSchemaNode(xmpImpl.getRoot(), schemaNS, false);
493 if (schemaNode != null)
494 {
495 if (removeSchemaChildren(schemaNode, doAllProperties))
496 {
497 xmpImpl.getRoot().removeChild(schemaNode);
498 }
499 }
500
501 if (includeAliases)
502 {
503 // We're removing the aliases also. Look them up by their
504 // namespace prefix.
505 // But that takes more code and the extra speed isn't worth it.
506 // Lookup the XMP node
507 // from the alias, to make sure the actual exists.
508
509 XMPAliasInfo[] aliases = XMPMetaFactory.getSchemaRegistry().findAliases(schemaNS);
510 for (int i = 0; i < aliases.length; i++)
511 {
512 XMPAliasInfo info = aliases[i];
513 XMPPath path = XMPPathParser.expandXPath(info.getNamespace(), info
514 .getPropName());
515 XMPNode actualProp = XMPNodeUtils
516 .findNode(xmpImpl.getRoot(), path, false, null);
517 if (actualProp != null)
518 {
519 XMPNode parent = actualProp.getParent();
520 parent.removeChild(actualProp);
521 }
522 }
523 }
524 }
525 else
526 {
527 // Remove all appropriate properties from all schema. In this case
528 // we don't have to be
529 // concerned with aliases, they are handled implicitly from the
530 // actual properties.
531 for (Iterator it = xmpImpl.getRoot().iterateChildren(); it.hasNext();)
532 {
533 XMPNode schema = (XMPNode) it.next();
534 if (removeSchemaChildren(schema, doAllProperties))
535 {
536 it.remove();
537 }
538 }
539 }
540 }
541
542
543 /**
544 * @see XMPUtils#appendProperties(XMPMeta, XMPMeta, boolean, boolean)
545 * @param source The source XMP object.
546 * @param destination The destination XMP object.
547 * @param doAllProperties Do internal properties in addition to external properties.
548 * @param replaceOldValues Replace the values of existing properties.
549 * @param deleteEmptyValues Delete destination values if source property is empty.
550 * @throws XMPException Forwards the Exceptions from the metadata processing
551 */
552 public static void appendProperties(XMPMeta source, XMPMeta destination,
553 boolean doAllProperties, boolean replaceOldValues, boolean deleteEmptyValues)
554 throws XMPException
555 {
556 ParameterAsserts.assertImplementation(source);
557 ParameterAsserts.assertImplementation(destination);
558
559 XMPMetaImpl src = (XMPMetaImpl) source;
560 XMPMetaImpl dest = (XMPMetaImpl) destination;
561
562 for (Iterator it = src.getRoot().iterateChildren(); it.hasNext();)
563 {
564 XMPNode sourceSchema = (XMPNode) it.next();
565
566 // Make sure we have a destination schema node
567 XMPNode destSchema = XMPNodeUtils.findSchemaNode(dest.getRoot(),
568 sourceSchema.getName(), false);
569 boolean createdSchema = false;
570 if (destSchema == null)
571 {
572 destSchema = new XMPNode(sourceSchema.getName(), sourceSchema.getValue(),
573 new PropertyOptions().setSchemaNode(true));
574 dest.getRoot().addChild(destSchema);
575 createdSchema = true;
576 }
577
578 // Process the source schema's children.
579 for (Iterator ic = sourceSchema.iterateChildren(); ic.hasNext();)
580 {
581 XMPNode sourceProp = (XMPNode) ic.next();
582 if (doAllProperties
583 || !Utils.isInternalProperty(sourceSchema.getName(), sourceProp.getName()))
584 {
585 appendSubtree(
586 dest, sourceProp, destSchema, false ,replaceOldValues, deleteEmptyValues);
587 }
588 }
589
590 if (!destSchema.hasChildren() && (createdSchema || deleteEmptyValues))
591 {
592 // Don't create an empty schema / remove empty schema.
593 dest.getRoot().removeChild(destSchema);
594 }
595 }
596 }
597
598
599 /**
600 * Remove all schema children according to the flag
601 * <code>doAllProperties</code>. Empty schemas are automatically remove
602 * by <code>XMPNode</code>
603 *
604 * @param schemaNode
605 * a schema node
606 * @param doAllProperties
607 * flag if all properties or only externals shall be removed.
608 * @return Returns true if the schema is empty after the operation.
609 */
610 private static boolean removeSchemaChildren(XMPNode schemaNode, boolean doAllProperties)
611 {
612 for (Iterator it = schemaNode.iterateChildren(); it.hasNext();)
613 {
614 XMPNode currProp = (XMPNode) it.next();
615 if (doAllProperties
616 || !Utils.isInternalProperty(schemaNode.getName(), currProp.getName()))
617 {
618 it.remove();
619 }
620 }
621
622 return !schemaNode.hasChildren();
623 }
624
625
626 /**
627 * @see XMPUtilsImpl#appendProperties(XMPMeta, XMPMeta, boolean, boolean, boolean)
628 * @param destXMP The destination XMP object.
629 * @param sourceNode the source node
630 * @param destParent the parent of the destination node
631 * @param replaceOldValues Replace the values of existing properties.
632 * @param deleteEmptyValues flag if properties with empty values should be deleted
633 * in the destination object.
634 * @throws XMPException
635 */
636 private static void appendSubtree(XMPMetaImpl destXMP, XMPNode sourceNode, XMPNode destParent, boolean mergeCompound,
637 boolean replaceOldValues, boolean deleteEmptyValues) throws XMPException
638 {
639 XMPNode destNode = XMPNodeUtils.findChildNode(destParent, sourceNode.getName(), false);
640
641 boolean valueIsEmpty = false;
642
643 valueIsEmpty = sourceNode.getOptions().isSimple() ?
644 sourceNode.getValue() == null || sourceNode.getValue().length() == 0 :
645 !sourceNode.hasChildren();
646
647
648 if(valueIsEmpty){
649 if ( deleteEmptyValues && (destNode != null) ) {
650 destParent.removeChild(destNode);
651 }
652 return; // ! Done, empty values are either ignored or cause deletions.
653 }
654
655 if (destNode == null)
656 {
657 // The one easy case, the destination does not exist.
658 XMPNode tempNode = (XMPNode) sourceNode.clone(true);
659 if(tempNode != null)
660 destParent.addChild(tempNode);
661 return;
662 }
663
664 PropertyOptions sourceForm = sourceNode.getOptions();
665
666 boolean replaceThis = replaceOldValues; // ! Don't modify replaceOld, it gets passed to inner calls.
667 if ( mergeCompound && (! sourceForm.isSimple()) ) {
668 replaceThis = false;
669 }
670
671 if (replaceThis)
672 {
673 // The destination exists and should be replaced.
674 // destXMP.setNode(destNode, sourceNode.getValue(), sourceNode.getOptions(), true);
675 destParent.removeChild(destNode);
676 //destNode = (XMPNode) sourceNode.clone();
677 XMPNode tempNode = (XMPNode) sourceNode.clone(true);
678 if(tempNode != null)
679 destParent.addChild(tempNode);
680 return;
681 }
682
683 // The destination exists and is not totally replaced. Structs and
684 // arrays are merged.
685
686
687 PropertyOptions destForm = destNode.getOptions();
688 if (sourceForm.getOptions() != destForm.getOptions() || sourceForm.isSimple())
689 {
690 return;
691 }
692
693 if (sourceForm.isStruct())
694 {
695 // To merge a struct process the fields recursively. E.g. add simple missing fields.
696 // The recursive call to AppendSubtree will handle deletion for fields with empty
697 // values.
698 for (Iterator it = sourceNode.iterateChildren(); it.hasNext();)
699 {
700 XMPNode sourceField = (XMPNode) it.next();
701 appendSubtree(destXMP, sourceField, destNode, mergeCompound,
702 replaceOldValues, deleteEmptyValues);
703 if (deleteEmptyValues && !destNode.hasChildren())
704 {
705 destParent.removeChild(destNode);
706 }
707 }
708 }
709 else if (sourceForm.isArrayAltText())
710 {
711 // Merge AltText arrays by the "xml:lang" qualifiers. Make sure x-default is first.
712 // Make a special check for deletion of empty values. Meaningful in AltText arrays
713 // because the "xml:lang" qualifier provides unambiguous source/dest correspondence.
714 for (Iterator it = sourceNode.iterateChildren(); it.hasNext();)
715 {
716 XMPNode sourceItem = (XMPNode) it.next();
717 if (!sourceItem.hasQualifier()
718 || !XMPConst.XML_LANG.equals(sourceItem.getQualifier(1).getName()))
719 {
720 continue;
721 }
722 int destIndex = XMPNodeUtils.lookupLanguageItem(destNode,
723 sourceItem.getQualifier(1).getValue());
724
725 if(sourceItem.getValue() == null || sourceItem.getValue().length() == 0){
726 if ( deleteEmptyValues && (destIndex != -1) ) {
727 destNode.removeChild(destIndex);
728 if (!destNode.hasChildren())
729 {
730 destParent.removeChild(destNode);
731 }
732 }
733 }
734 else {
735 if (destIndex == -1) {
736 // Not replacing, keep the existing item.
737 if (!XMPConst.X_DEFAULT.equals(sourceItem.getQualifier(1).getValue())
738 || !destNode.hasChildren()) {
739 XMPNode tempNode = (XMPNode) sourceItem.clone(true);
740 if (tempNode != null)
741 destNode.addChild(tempNode);
742 // sourceItem.cloneSubtree(destNode);
743 } else {
744 XMPNode destItem = new XMPNode(sourceItem.getName(), sourceItem.getValue(),
745 sourceItem.getOptions());
746 sourceItem.cloneSubtree(destItem, true);
747 destNode.addChild(1, destItem);
748 }
749 }
750 else{
751 if(replaceOldValues)
752 destNode.getChild(destIndex).setValue(sourceItem.getValue());
753 }
754 }
755 }
756 }
757 else if (sourceForm.isArray())
758 {
759 // Merge other arrays by item values. Don't worry about order or duplicates. Source
760 // items with empty values do not cause deletion, that conflicts horribly with
761 // merging.
762 for (Iterator is = sourceNode.iterateChildren(); is.hasNext();)
763 {
764 XMPNode sourceItem = (XMPNode) is.next();
765 boolean match = false;
766 for (Iterator id = destNode.iterateChildren(); id.hasNext();)
767 {
768 XMPNode destItem = (XMPNode) id.next();
769 if (itemValuesMatch(sourceItem, destItem))
770 {
771 match = true;
772 break;
773 }
774 }
775 if (!match)
776 {
777 XMPNode tempNode = (XMPNode) sourceItem.clone(true);
778 if(tempNode != null)
779 destNode.addChild(tempNode);
780 }
781 }
782 }
783 }
784
785
786
787 /**
788 * Compares two nodes including its children and qualifier.
789 * @param leftNode an <code>XMPNode</code>
790 * @param rightNode an <code>XMPNode</code>
791 * @return Returns true if the nodes are equal, false otherwise.
792 * @throws XMPException Forwards exceptions to the calling method.
793 */
794 private static boolean itemValuesMatch(XMPNode leftNode, XMPNode rightNode) throws XMPException
795 {
796 PropertyOptions leftForm = leftNode.getOptions();
797 PropertyOptions rightForm = rightNode.getOptions();
798
799 if (!leftForm.equals(rightForm))
800 {
801 return false;
802 }
803
804 if (leftForm.isSimple())
805 {
806 // Simple nodes, check the values and xml:lang qualifiers.
807 if (!leftNode.getValue().equals(rightNode.getValue()))
808 {
809 return false;
810 }
811 if (leftNode.getOptions().getHasLanguage() != rightNode.getOptions().getHasLanguage())
812 {
813 return false;
814 }
815 if (leftNode.getOptions().getHasLanguage()
816 && !leftNode.getQualifier(1).getValue().equals(
817 rightNode.getQualifier(1).getValue()))
818 {
819 return false;
820 }
821 }
822 else if (leftForm.isStruct())
823 {
824 // Struct nodes, see if all fields match, ignoring order.
825
826 if (leftNode.getChildrenLength() != rightNode.getChildrenLength())
827 {
828 return false;
829 }
830
831 for (Iterator it = leftNode.iterateChildren(); it.hasNext();)
832 {
833 XMPNode leftField = (XMPNode) it.next();
834 XMPNode rightField = XMPNodeUtils.findChildNode(rightNode, leftField.getName(),
835 false);
836 if (rightField == null || !itemValuesMatch(leftField, rightField))
837 {
838 return false;
839 }
840 }
841 }
842 else
843 {
844 // Array nodes, see if the "leftNode" values are present in the
845 // "rightNode", ignoring order, duplicates,
846 // and extra values in the rightNode-> The rightNode is the
847 // destination for AppendProperties.
848
849 assert leftForm.isArray();
850
851 for (Iterator il = leftNode.iterateChildren(); il.hasNext();)
852 {
853 XMPNode leftItem = (XMPNode) il.next();
854
855 boolean match = false;
856 for (Iterator ir = rightNode.iterateChildren(); ir.hasNext();)
857 {
858 XMPNode rightItem = (XMPNode) ir.next();
859 if (itemValuesMatch(leftItem, rightItem))
860 {
861 match = true;
862 break;
863 }
864 }
865 if (!match)
866 {
867 return false;
868 }
869 }
870 }
871 return true; // All of the checks passed.
872 }
873
874 public static void duplicateSubtree(XMPMeta source, XMPMeta dest, String sourceNS,
875 String sourceRoot, String destNS, String destRoot, PropertyOptions options) throws XMPException{
876
877 boolean fullSourceTree = false;
878 boolean fullDestTree = false;
879 XMPPath sourcePath, destPath;
880 XMPNode sourceNode = null;
881 XMPNode destNode = null;
882
883 ParameterAsserts.assertNotNull(source);
884 ParameterAsserts.assertSchemaNS(sourceNS);
885 ParameterAsserts.assertSchemaNS(sourceRoot);
886 ParameterAsserts.assertNotNull(dest);
887 ParameterAsserts.assertNotNull(destNS);
888 ParameterAsserts.assertNotNull(destRoot);
889
890 if(destNS.length() == 0){
891 destNS = sourceNS;
892 }
893
894 if(destRoot.length() == 0){
895 destRoot = sourceRoot;
896 }
897
898 if(sourceNS.equals("*")){
899 fullSourceTree = true;
900 }
901
902 if(destNS.equals("*")){
903 fullDestTree = true;
904 }
905
906 if ( (source == dest) && (fullSourceTree | fullDestTree) ) {
907 throw new XMPException("Can't duplicate tree onto itself", XMPError.BADPARAM);
908 }
909 if ( fullSourceTree & fullDestTree ) {
910 throw new XMPException( "Use Clone for full tree to full tree", XMPError.BADPARAM);
911 }
912 if(fullSourceTree){
913 destPath = XMPPathParser.expandXPath(destNS, destRoot);
914 XMPMetaImpl destImpl = (XMPMetaImpl)dest;
915 destNode = XMPNodeUtils.findNode(destImpl.getRoot(), destPath, false, null);
916 if(destNode == null || !(destNode.getOptions().isStruct()))
917 throw new XMPException("Destination must be an existing struct", XMPError.BADXPATH);
918
919 if(destNode.hasChildren()){
920 if((options != null) && ((options.getOptions() & PropertyOptions.DELETE_EXISTING) != 0)){
921 destNode.removeChildren();
922 }
923 else{
924 throw new XMPException("Destination must be an empty struct", XMPError.BADXPATH);
925 }
926 }
927
928 XMPMetaImpl sourceImpl = (XMPMetaImpl)source;
929 for ( int schemaNum = 1, schemaLim = sourceImpl.getRoot().getChildrenLength(); schemaNum <= schemaLim; ++schemaNum ) {
930
931 XMPNode currSchema = sourceImpl.getRoot().getChild(schemaNum);
932
933 for ( int propNum = 1, propLim = currSchema.getChildrenLength(); propNum <= propLim; ++propNum ) {
934 sourceNode = currSchema.getChild(propNum);
935 destNode.addChild((XMPNode)sourceNode.clone(false));
936
937 /*XMP_Node * copyNode = new XMP_Node ( destNode, sourceNode->name, sourceNode->value, sourceNode->options );
938 destNode->children.push_back ( copyNode );
939 CloneOffspring ( sourceNode, copyNode );*/ //implemented above
940 }
941
942 }
943
944 }
945 else if(fullDestTree){
946
947 // The source node must be an existing struct, copy all of the fields to the dest top level.
948
949 XMPMetaImpl srcImpl = (XMPMetaImpl)source;
950 XMPMetaImpl dstImpl = (XMPMetaImpl)dest;
951 sourcePath = XMPPathParser.expandXPath ( sourceNS, sourceRoot );
952 sourceNode = XMPNodeUtils.findNode ( srcImpl.getRoot() , sourcePath , false, null);
953
954 if ( (sourceNode == null) || !( sourceNode.getOptions().isStruct()) ) {
955 throw new XMPException("Source must be an existing struct", XMPError.BADXPATH);
956 }
957
958 destNode = dstImpl.getRoot();
959
960 if ( destNode.hasChildren() ) {
961 if((options != null) && ((options.getOptions() & PropertyOptions.DELETE_EXISTING) != 0)) {
962 destNode.removeChildren();
963 } else {
964 throw new XMPException("Source must be an existing struct", XMPError.BADXPATH);
965 }
966 }
967
968 String nsPrefix;
969
970 for ( int fieldNum = 1, fieldLim = sourceNode.getChildrenLength(); fieldNum <= fieldLim; ++fieldNum ) {
971
972 XMPNode currField = sourceNode.getChild(fieldNum);
973
974 int colonPos = currField.getName().indexOf(':');
975 if ( colonPos == -1 ) continue;
976 nsPrefix = new String ( currField.getName().substring(0, colonPos+1));
977
978 XMPSchemaRegistry nsRegister = XMPMetaFactory.getSchemaRegistry();
979 String nsURI = nsRegister.getNamespaceURI(nsPrefix);
980
981 if(nsURI == null){
982 throw new XMPException("Source field namespace is not global", XMPError.BADSCHEMA);
983 }
984
985 XMPNode destSchema = XMPNodeUtils.findSchemaNode ( dstImpl.getRoot(), nsURI, true );
986 if ( destSchema == null){
987 throw new XMPException("Failed to find destination schema", XMPError.BADSCHEMA);
988 }
989
990 destSchema.addChild((XMPNode)currField.clone(false));
991 }
992 }
993 else{
994 sourcePath = XMPPathParser.expandXPath(sourceNS, sourceRoot);
995 destPath = XMPPathParser.expandXPath(destNS, destRoot);
996 XMPMetaImpl sourceImpl = (XMPMetaImpl)source;
997 XMPMetaImpl destImpl = (XMPMetaImpl)dest;
998 sourceNode = XMPNodeUtils.findNode(sourceImpl.getRoot(), sourcePath, false, null);
999 if(sourceNode == null)
1000 throw new XMPException("Can't find source subtree", XMPError.BADXPATH);
1001 destNode = XMPNodeUtils.findNode(destImpl.getRoot(), destPath, false, null);
1002 if(destNode != null)
1003 throw new XMPException("Destination subtree must not exist", XMPError.BADXPATH);
1004 destNode = XMPNodeUtils.findNode(destImpl.getRoot(), destPath, true, null);
1005 if(destNode == null)
1006 throw new XMPException("Can't create destination root node", XMPError.BADXPATH);
1007 if ( source == dest ) {
1008 for ( XMPNode testNode = destNode; testNode != null; testNode = testNode.getParent() ) {
1009 if ( testNode == sourceNode ) {
1010 // *** delete the just-created dest root node
1011 throw new XMPException("Destination subtree is within the source subtree", XMPError.BADXPATH);
1012 }
1013 }
1014 }
1015 destNode.setValue(sourceNode.getValue());
1016 destNode.setOptions(sourceNode.getOptions());
1017 sourceNode.cloneSubtree(destNode, false);
1018 }
1019
1020 }
1021
1022
1023
1024
1025
1026
1027 /**
1028 * Make sure the separator is OK. It must be one semicolon surrounded by
1029 * zero or more spaces. Any of the recognized semicolons or spaces are
1030 * allowed.
1031 *
1032 * @param separator
1033 * @throws XMPException
1034 */
1035 private static void checkSeparator(String separator) throws XMPException
1036 {
1037 boolean haveSemicolon = false;
1038 for (int i = 0; i < separator.length(); i++)
1039 {
1040 int charKind = classifyCharacter(separator.charAt(i));
1041 if (charKind == UCK_SEMICOLON)
1042 {
1043 if (haveSemicolon)
1044 {
1045 throw new XMPException("Separator can have only one semicolon",
1046 XMPError.BADPARAM);
1047 }
1048 haveSemicolon = true;
1049 }
1050 else if (charKind != UCK_SPACE)
1051 {
1052 throw new XMPException("Separator can have only spaces and one semicolon",
1053 XMPError.BADPARAM);
1054 }
1055 }
1056 if (!haveSemicolon)
1057 {
1058 throw new XMPException("Separator must have one semicolon", XMPError.BADPARAM);
1059 }
1060 }
1061
1062
1063 /**
1064 * Make sure the open and close quotes are a legitimate pair and return the
1065 * correct closing quote or an exception.
1066 *
1067 * @param quotes
1068 * opened and closing quote in a string
1069 * @param openQuote
1070 * the open quote
1071 * @return Returns a corresponding closing quote.
1072 * @throws XMPException
1073 */
1074 private static char checkQuotes(String quotes, char openQuote) throws XMPException
1075 {
1076 char closeQuote;
1077
1078 int charKind = classifyCharacter(openQuote);
1079 if (charKind != UCK_QUOTE)
1080 {
1081 throw new XMPException("Invalid quoting character", XMPError.BADPARAM);
1082 }
1083
1084 if (quotes.length() == 1)
1085 {
1086 closeQuote = openQuote;
1087 }
1088 else
1089 {
1090 closeQuote = quotes.charAt(1);
1091 charKind = classifyCharacter(closeQuote);
1092 if (charKind != UCK_QUOTE)
1093 {
1094 throw new XMPException("Invalid quoting character", XMPError.BADPARAM);
1095 }
1096 }
1097
1098 if (closeQuote != getClosingQuote(openQuote))
1099 {
1100 throw new XMPException("Mismatched quote pair", XMPError.BADPARAM);
1101 }
1102 return closeQuote;
1103 }
1104
1105
1106 /**
1107 * Classifies the character into normal chars, spaces, semicola, quotes,
1108 * control chars.
1109 *
1110 * @param ch
1111 * a char
1112 * @return Return the character kind.
1113 */
1114 private static int classifyCharacter(char ch)
1115 {
1116 if (SPACES.indexOf(ch) >= 0 || (0x2000 <= ch && ch <= 0x200B))
1117 {
1118 return UCK_SPACE;
1119 }
1120 else if (COMMAS.indexOf(ch) >= 0)
1121 {
1122 return UCK_COMMA;
1123 }
1124 else if (SEMICOLA.indexOf(ch) >= 0)
1125 {
1126 return UCK_SEMICOLON;
1127 }
1128 else if (QUOTES.indexOf(ch) >= 0 || (0x3008 <= ch && ch <= 0x300F)
1129 || (0x2018 <= ch && ch <= 0x201F))
1130 {
1131 return UCK_QUOTE;
1132 }
1133 else if (ch < 0x0020 || CONTROLS.indexOf(ch) >= 0)
1134 {
1135 return UCK_CONTROL;
1136 }
1137 else
1138 {
1139 // Assume typical case.
1140 return UCK_NORMAL;
1141 }
1142 }
1143
1144
1145 /**
1146 * @param openQuote
1147 * the open quote char
1148 * @return Returns the matching closing quote for an open quote.
1149 */
1150 private static char getClosingQuote(char openQuote)
1151 {
1152 switch (openQuote)
1153 {
1154 case 0x0022:
1155 return 0x0022; // ! U+0022 is both opening and closing.
1156 // Not interpreted as brackets anymore
1157 // case 0x005B:
1158 // return 0x005D;
1159 case 0x00AB:
1160 return 0x00BB; // ! U+00AB and U+00BB are reversible.
1161 case 0x00BB:
1162 return 0x00AB;
1163 case 0x2015:
1164 return 0x2015; // ! U+2015 is both opening and closing.
1165 case 0x2018:
1166 return 0x2019;
1167 case 0x201A:
1168 return 0x201B;
1169 case 0x201C:
1170 return 0x201D;
1171 case 0x201E:
1172 return 0x201F;
1173 case 0x2039:
1174 return 0x203A; // ! U+2039 and U+203A are reversible.
1175 case 0x203A:
1176 return 0x2039;
1177 case 0x3008:
1178 return 0x3009;
1179 case 0x300A:
1180 return 0x300B;
1181 case 0x300C:
1182 return 0x300D;
1183 case 0x300E:
1184 return 0x300F;
1185 case 0x301D:
1186 return 0x301F; // ! U+301E also closes U+301D.
1187 default:
1188 return 0;
1189 }
1190 }
1191
1192
1193 /**
1194 * Add quotes to the item.
1195 *
1196 * @param item
1197 * the array item
1198 * @param openQuote
1199 * the open quote character
1200 * @param closeQuote
1201 * the closing quote character
1202 * @param allowCommas
1203 * flag if commas are allowed
1204 * @return Returns the value in quotes.
1205 */
1206 private static String applyQuotes(String item, char openQuote, char closeQuote,
1207 boolean allowCommas)
1208 {
1209 if (item == null)
1210 {
1211 item = "";
1212 }
1213
1214 boolean prevSpace = false;
1215 int charOffset;
1216 int charKind;
1217
1218 // See if there are any separators in the value. Stop at the first
1219 // occurrance. This is a bit
1220 // tricky in order to make typical typing work conveniently. The purpose
1221 // of applying quotes
1222 // is to preserve the values when splitting them back apart. That is
1223 // CatenateContainerItems
1224 // and SeparateContainerItems must round trip properly. For the most
1225 // part we only look for
1226 // separators here. Internal quotes, as in -- Irving "Bud" Jones --
1227 // won't cause problems in
1228 // the separation. An initial quote will though, it will make the value
1229 // look quoted.
1230
1231 int i;
1232 for (i = 0; i < item.length(); i++)
1233 {
1234 char ch = item.charAt(i);
1235 charKind = classifyCharacter(ch);
1236 if (i == 0 && charKind == UCK_QUOTE)
1237 {
1238 break;
1239 }
1240
1241 if (charKind == UCK_SPACE)
1242 {
1243 // Multiple spaces are a separator.
1244 if (prevSpace)
1245 {
1246 break;
1247 }
1248 prevSpace = true;
1249 }
1250 else
1251 {
1252 prevSpace = false;
1253 if ((charKind == UCK_SEMICOLON || charKind == UCK_CONTROL)
1254 || (charKind == UCK_COMMA && !allowCommas))
1255 {
1256 break;
1257 }
1258 }
1259 }
1260
1261
1262 if (i < item.length())
1263 {
1264 // Create a quoted copy, doubling any internal quotes that match the
1265 // outer ones. Internal quotes did not stop the "needs quoting"
1266 // search, but they do need
1267 // doubling. So we have to rescan the front of the string for
1268 // quotes. Handle the special
1269 // case of U+301D being closed by either U+301E or U+301F.
1270
1271 StringBuffer newItem = new StringBuffer(item.length() + 2);
1272 int splitPoint;
1273 for (splitPoint = 0; splitPoint <= i; splitPoint++)
1274 {
1275 if (classifyCharacter(item.charAt(i)) == UCK_QUOTE)
1276 {
1277 break;
1278 }
1279 }
1280
1281 // Copy the leading "normal" portion.
1282 newItem.append(openQuote).append(item.substring(0, splitPoint));
1283
1284 for (charOffset = splitPoint; charOffset < item.length(); charOffset++)
1285 {
1286 newItem.append(item.charAt(charOffset));
1287 if (classifyCharacter(item.charAt(charOffset)) == UCK_QUOTE
1288 && isSurroundingQuote(item.charAt(charOffset), openQuote, closeQuote))
1289 {
1290 newItem.append(item.charAt(charOffset));
1291 }
1292 }
1293
1294 newItem.append(closeQuote);
1295
1296 item = newItem.toString();
1297 }
1298
1299 return item;
1300 }
1301
1302
1303 /**
1304 * @param ch a character
1305 * @param openQuote the opening quote char
1306 * @param closeQuote the closing quote char
1307 * @return Return it the character is a surrounding quote.
1308 */
1309 private static boolean isSurroundingQuote(char ch, char openQuote, char closeQuote)
1310 {
1311 return ch == openQuote || isClosingingQuote(ch, openQuote, closeQuote);
1312 }
1313
1314
1315 /**
1316 * @param ch a character
1317 * @param openQuote the opening quote char
1318 * @param closeQuote the closing quote char
1319 * @return Returns true if the character is a closing quote.
1320 */
1321 private static boolean isClosingingQuote(char ch, char openQuote, char closeQuote)
1322 {
1323 return ch == closeQuote || (openQuote == 0x301D && ch == 0x301E || ch == 0x301F);
1324 }
1325
1326
1327
1328 /**
1329 * U+0022 ASCII space<br>
1330 * U+3000, ideographic space<br>
1331 * U+303F, ideographic half fill space<br>
1332 * U+2000..U+200B, en quad through zero width space
1333 */
1334 private static final String SPACES = "\u0020\u3000\u303F";
1335 /**
1336 * U+002C, ASCII comma<br>
1337 * U+FF0C, full width comma<br>
1338 * U+FF64, half width ideographic comma<br>
1339 * U+FE50, small comma<br>
1340 * U+FE51, small ideographic comma<br>
1341 * U+3001, ideographic comma<br>
1342 * U+060C, Arabic comma<br>
1343 * U+055D, Armenian comma
1344 */
1345 private static final String COMMAS = "\u002C\uFF0C\uFF64\uFE50\uFE51\u3001\u060C\u055D";
1346 /**
1347 * U+003B, ASCII semicolon<br>
1348 * U+FF1B, full width semicolon<br>
1349 * U+FE54, small semicolon<br>
1350 * U+061B, Arabic semicolon<br>
1351 * U+037E, Greek "semicolon" (really a question mark)
1352 */
1353 private static final String SEMICOLA = "\u003B\uFF1B\uFE54\u061B\u037E";
1354 /**
1355 * U+0022 ASCII quote<br>
1356 * The square brackets are not interpreted as quotes anymore (bug #2674672)
1357 * (ASCII '[' (0x5B) and ']' (0x5D) are used as quotes in Chinese and
1358 * Korean.)<br>
1359 * U+00AB and U+00BB, guillemet quotes<br>
1360 * U+3008..U+300F, various quotes.<br>
1361 * U+301D..U+301F, double prime quotes.<br>
1362 * U+2015, dash quote.<br>
1363 * U+2018..U+201F, various quotes.<br>
1364 * U+2039 and U+203A, guillemet quotes.
1365 */
1366 private static final String QUOTES =
1367 "\"\u00AB\u00BB\u301D\u301E\u301F\u2015\u2039\u203A";
1368 // "\"\u005B\u005D\u00AB\u00BB\u301D\u301E\u301F\u2015\u2039\u203A";
1369 /**
1370 * U+0000..U+001F ASCII controls<br>
1371 * U+2028, line separator.<br>
1372 * U+2029, paragraph separator.
1373 */
1374 private static final String CONTROLS = "\u2028\u2029";
1375
1376 /**
1377 * Moves the specified Property from one Meta to another.
1378 *
1379 * @param stdXMP
1380 * Meta Object from where the property needs to move
1381 * @param extXMP
1382 * Meta Object to where the property needs to move
1383 * @param schemaURI
1384 * Schema of the specified property
1385 * @param propName
1386 * Name of the property
1387 *
1388 * @return true in case of success otherwise false.
1389 *
1390 * @throws XMPException in case of failure
1391 */
1392
1393 static boolean moveOneProperty(XMPMetaImpl stdXMP, XMPMetaImpl extXMP, String schemaURI, String propName)
1394 throws XMPException {
1395
1396 XMPNode propNode = null;
1397
1398 XMPNode stdSchema = XMPNodeUtils.findSchemaNode(stdXMP.getRoot(), schemaURI, false);
1399 if (stdSchema != null) {
1400 propNode = XMPNodeUtils.findChildNode(stdSchema, propName, false);
1401 }
1402 if (propNode == null)
1403 return false;
1404
1405 XMPNode extSchema = XMPNodeUtils.findSchemaNode(extXMP.getRoot(), schemaURI, true);
1406
1407 propNode.setParent(extSchema);
1408
1409 extSchema.setImplicit(false);
1410 extSchema.addChild(propNode);
1411
1412 stdSchema.removeChild(propNode);
1413
1414 if (stdSchema.hasChildren() == false) {
1415 XMPNode xmpTree = stdSchema.getParent();
1416 xmpTree.removeChild(stdSchema);
1417 }
1418
1419 return true;
1420 }
1421
1422 /**
1423 * estimates the size of an xmp node
1424 *
1425 * @param xmpNode
1426 * XMP Node Object
1427 *
1428 * @return the estimated size of the node
1429 *
1430 */
1431 static int estimateSizeForJPEG(XMPNode xmpNode) {
1432 int estSize = 0;
1433 int nameSize = xmpNode.getName().length();
1434
1435 boolean includeName = (!xmpNode.getOptions().isArray());
1436
1437 if (xmpNode.getOptions().isSimple()) {
1438
1439 if (includeName)
1440 estSize += (nameSize + 3); // Assume attribute form.
1441 estSize += xmpNode.getValue().length();
1442
1443 } else if (xmpNode.getOptions().isArray()) {
1444
1445 // The form of the value portion is:
1446 // <rdf:Xyz><rdf:li>...</rdf:li>...</rdf:Xyx>
1447 if (includeName)
1448 estSize += (2 * nameSize + 5);
1449 int arraySize = xmpNode.getChildrenLength();
1450 estSize += 9 + 10; // The rdf:Xyz tags.
1451 estSize += arraySize * (8 + 9); // The rdf:li tags.
1452 for (int i = 1; i <= arraySize; ++i) {
1453 estSize += estimateSizeForJPEG(xmpNode.getChild(i));
1454 }
1455 } else {
1456
1457 // The form is: <headTag
1458 // rdf:parseType="Resource">...fields...</tailTag>
1459 if (includeName)
1460 estSize += (2 * nameSize + 5);
1461 estSize += 25; // The rdf:parseType="Resource" attribute.
1462 int fieldCount = xmpNode.getChildrenLength();
1463 for (int i = 1; i <= fieldCount; ++i) {
1464 estSize += estimateSizeForJPEG(xmpNode.getChild(i));
1465 }
1466
1467 }
1468 return estSize;
1469 }
1470
1471 /**
1472 * Utility function for placing objects in a Map. It behaves like a multi map.
1473 *
1474 * @param multiMap
1475 * A Map object which takes Integer as a key and list of list of String as value
1476 * @param key
1477 * A Key for the map
1478 * @param stringPair
1479 * A value for the map
1480 *
1481 */
1482 private static void putObjectsInMultiMap(Map<Integer, List<List<String>>> multiMap, Integer key,
1483 List<String> stringPair) {
1484 if (multiMap == null)
1485 return;
1486 List<List<String>> tempList = multiMap.get(key);
1487 if (tempList == null) {
1488 tempList = new ArrayList<List<String>>();
1489 multiMap.put(key, tempList);
1490 }
1491 tempList.add(stringPair);
1492 }
1493
1494 /**
1495 * Utility function for retrieving biggest entry in the multimap
1496 *
1497 * @see estimateSizeForJPEG for size calculation
1498 *
1499 * @param multiMap
1500 * A Map object which takes Integer as a key and list of list of String as value
1501 *
1502 * @return the list with the maximum size.
1503 *
1504 */
1505 private static List<String> getBiggestEntryInMultiMap(Map<Integer, List<List<String>>> multiMap) {
1506 if (multiMap == null || multiMap.isEmpty())
1507 return null;
1508
1509 List<List<String>> myList = multiMap.get(((TreeMap) multiMap).lastKey());
1510 List<String> myList1 = myList.get(0);
1511 myList.remove(0);
1512 if (myList.isEmpty()) {
1513 multiMap.remove(((TreeMap) multiMap).lastKey());
1514 }
1515 return myList1;
1516 }
1517
1518 /**
1519 * Utility function for creating esimated size map for different properties of XMP Packet.
1520 *
1521 * @see packageForJPEG
1522 *
1523 * @param stdXMP
1524 * Meta Object whose property sizes needs to calculate.
1525 *
1526 * @param propSizes
1527 * A treeMap Object which takes Integer as a key and list of list of String as values
1528 *
1529 */
1530
1531 static void createEstimatedSizeMap(XMPMetaImpl stdXMP, Map<Integer, List<List<String>>> propSizes) {
1532
1533 for (int s = stdXMP.getRoot().getChildrenLength(); s > 0; --s) {
1534 XMPNode stdSchema = stdXMP.getRoot().getChild(s);
1535 for (int p = stdSchema.getChildrenLength(); p > 0; --p) {
1536 XMPNode stdProp = stdSchema.getChild(p);
1537 if ((stdSchema.getName().equals(XMPConst.NS_XMP_NOTE))
1538 && (stdProp.getName().equals("xmpNote:HasExtendedXMP")))
1539 continue; // ! Don't move xmpNote:HasExtendedXMP.
1540
1541 int propSize = estimateSizeForJPEG(stdProp);
1542 List<String> namePair = new ArrayList<String>();
1543 namePair.add(stdSchema.getName());
1544 namePair.add(stdProp.getName());
1545 putObjectsInMultiMap(propSizes, propSize, namePair);
1546 }
1547 }
1548 }
1549
1550 /**
1551 * Utility function for moving the largest property from One XMP Packet to another.
1552 *
1553 * @see moveOneProperty
1554 * @see packageForJPEG
1555 *
1556 * @param stdXMP
1557 * Meta Object from where property moves.
1558 *
1559 * @param extXMP
1560 * Meta Object to where property moves.
1561 *
1562 * @param propSizes
1563 * A treeMap Object which holds the estimated sizes of the property of stdXMP as a key and
1564 * their string representation as map values.
1565 *
1566 */
1567 static int moveLargestProperty(XMPMetaImpl stdXMP, XMPMetaImpl extXMP, Map<Integer, List<List<String>>> propSizes)
1568 throws XMPException {
1569 assert (!propSizes.isEmpty());
1570
1571 @SuppressWarnings("rawtypes")
1572 int propSize = (Integer) ((TreeMap) propSizes).lastKey();
1573 List<String> tempList = getBiggestEntryInMultiMap(propSizes);
1574 String schemaURI = tempList.get(0);
1575 String propName = tempList.get(1);
1576
1577 boolean moved = moveOneProperty(stdXMP, extXMP, schemaURI, propName);
1578 assert (moved);
1579 return propSize;
1580
1581 }
1582
1583 /**
1584 * creates XMP serializations appropriate for a JPEG file.
1585 *
1586 * The standard XMP in a JPEG file is limited to 64K bytes. This function
1587 * serializes the XMP metadata in an XMP object into a string of RDF . If
1588 * the data does not fit into the 64K byte limit, it creates a second packet
1589 * string with the extended data.
1590 *
1591 * @param origXMPImpl
1592 * The XMP object containing the metadata.
1593 *
1594 * @param stdStr
1595 * A string object in which to return the full standard XMP
1596 * packet.
1597 *
1598 * @param extStr
1599 * A string object in which to return the serialized extended
1600 * XMP, empty if not needed.
1601 *
1602 * @param digestStr
1603 * A string object in which to return an MD5 digest of the
1604 * serialized extended XMP, empty if not needed.
1605 *
1606 * @throws NoSuchAlgorithmException if fail to find algorithm for MD5
1607 * @throws XMPException in case of internal error occurs.
1608 *
1609 */
1610
1611 public static void packageForJPEG ( XMPMeta origXMPImpl,
1612 StringBuilder stdStr,
1613 StringBuilder extStr,
1614 StringBuilder digestStr ) throws XMPException, NoSuchAlgorithmException
1615 {
1616 XMPMetaImpl origXMP = (XMPMetaImpl) origXMPImpl;
1617 assert ( (stdStr != null) && (extStr != null) && (digestStr != null) ); // ! Enforced by wrapper.
1618
1619 final int kStdXMPLimit = 65000 ;
1620 final String kPacketTrailer = "<?xpacket end=\"w\"?>";
1621 final int kTrailerLen = kPacketTrailer.length();
1622
1623 String tempStr = null;
1624 XMPMetaImpl stdXMP = new XMPMetaImpl();
1625 XMPMetaImpl extXMP = new XMPMetaImpl();
1626 SerializeOptions keepItSmall = new SerializeOptions(SerializeOptions.USE_COMPACT_FORMAT);
1627 keepItSmall.setPadding(0);
1628 keepItSmall.setIndent("");
1629 keepItSmall.setBaseIndent(0);
1630 keepItSmall.setNewline(" ");
1631
1632
1633 // Try to serialize everything. Note that we're making internal calls to SerializeToBuffer, so
1634 // we'll be getting back the pointer and length for its internal string.
1635
1636
1637 tempStr = XMPMetaFactory.serializeToString(origXMP,keepItSmall);
1638
1639 if ( tempStr.length() > kStdXMPLimit ) {
1640
1641 // Couldn't fit everything, make a copy of the input XMP and make sure there is no xmp:Thumbnails property.
1642
1643 stdXMP.getRoot().setOptions(origXMP.getRoot().getOptions()) ;
1644 stdXMP.getRoot().setName(origXMP.getRoot().getName()) ;
1645 stdXMP.getRoot().setValue(origXMP.getRoot().getValue());
1646
1647 origXMP.getRoot().cloneSubtree(stdXMP.getRoot(), false);
1648
1649 if ( stdXMP.doesPropertyExist ( XMPConst.NS_XMP, "Thumbnails" ) ) {
1650 stdXMP.deleteProperty ( XMPConst.NS_XMP, "Thumbnails" );
1651 tempStr = XMPMetaFactory.serializeToString(stdXMP,keepItSmall);
1652 }
1653
1654 }
1655
1656 if ( tempStr.length() > kStdXMPLimit ) {
1657
1658 // Still doesn't fit, move all of the Camera Raw namespace. Add a dummy value for xmpNote:HasExtendedXMP.
1659
1660 stdXMP.setProperty ( XMPConst.NS_XMP_NOTE, "HasExtendedXMP", "123456789-123456789-123456789-12",
1661 new PropertyOptions(PropertyOptions.NO_OPTIONS));
1662
1663
1664 XMPNode crSchema = XMPNodeUtils.findSchemaNode(stdXMP.getRoot(), XMPConst.NS_CAMERARAW, false);
1665
1666 if ( crSchema != null ) {
1667 crSchema.setParent(extXMP.getRoot());
1668 extXMP.getRoot().addChild(crSchema);
1669 stdXMP.getRoot().removeChild(crSchema);
1670
1671 tempStr = XMPMetaFactory.serializeToString(stdXMP,keepItSmall);
1672 }
1673
1674 }
1675
1676 if ( tempStr.length() > kStdXMPLimit ) {
1677
1678 // Still doesn't fit, move photoshop:History.
1679
1680 boolean moved = moveOneProperty ( stdXMP, extXMP, XMPConst.NS_PHOTOSHOP, "photoshop:History" );
1681
1682 if ( moved ) {
1683 tempStr = XMPMetaFactory.serializeToString(stdXMP,keepItSmall);
1684 }
1685
1686 }
1687
1688 if ( tempStr.length() > kStdXMPLimit ) {
1689
1690 // Still doesn't fit, move top level properties in order of estimated size. This is done by
1691 // creating a multi-map that maps the serialized size to the string pair for the schema URI
1692 // and top level property name. Since maps are inherently ordered, a reverse iteration of
1693 // the map can be done to move the largest things first. We use a double loop to keep going
1694 // until the serialization actually fits, in case the estimates are off.
1695
1696 Map<Integer,List<List<String>>> propSizes = new TreeMap<Integer,List<List<String>>>();
1697 createEstimatedSizeMap ( stdXMP, propSizes );
1698
1699 // Outer loop to make sure enough is actually moved.
1700
1701 while ( (tempStr.length() > kStdXMPLimit) && (! propSizes.isEmpty()) ) {
1702
1703 // Inner loop, move what seems to be enough according to the estimates.
1704
1705 int tempLen = tempStr.length();
1706 while ( (tempLen > kStdXMPLimit) && (! propSizes.isEmpty()) ) {
1707
1708 int propSize = moveLargestProperty ( stdXMP, extXMP, propSizes );
1709 assert ( propSize > 0 );
1710
1711 if ( propSize > tempLen ) propSize = tempLen; // ! Don't go negative.
1712 tempLen -= propSize;
1713
1714 }
1715
1716 // Reserialize the remaining standard XMP.
1717
1718 tempStr = XMPMetaFactory.serializeToString(stdXMP,keepItSmall);
1719 }
1720
1721 }
1722
1723 if ( tempStr.length() > kStdXMPLimit ) {
1724 // Still doesn't fit, throw an exception and let the client decide what to do.
1725 // ! This should never happen with the policy of moving any and all top level properties.
1726 throw new XMPException( "Can't reduce XMP enough for JPEG file", XMPError.INTERNALFAILURE );
1727 }
1728
1729 // Set the static output strings.
1730
1731 if ( extXMP.getRoot().getChildrenLength() == 0 ) {
1732
1733 // Just have the standard XMP.
1734 stdStr.append(tempStr);
1735
1736
1737 } else {
1738
1739 // Have extended XMP. Serialize it, compute the digest, reset xmpNote:HasExtendedXMP, and
1740 // reserialize the standard XMP.
1741
1742
1743 tempStr = XMPMetaFactory.serializeToString(extXMP,
1744 new SerializeOptions(SerializeOptions.USE_COMPACT_FORMAT | SerializeOptions.OMIT_PACKET_WRAPPER));
1745
1746 extStr.append(tempStr);
1747
1748 MessageDigest md = MessageDigest.getInstance("MD5");
1749 md.update(tempStr.getBytes());
1750
1751 byte byteData[] = md.digest();
1752
1753 for (int i = 0; i < byteData.length; i++) {
1754 digestStr.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
1755 }
1756
1757 stdXMP.setProperty ( XMPConst.NS_XMP_NOTE, "HasExtendedXMP", digestStr.toString(),
1758 new PropertyOptions(PropertyOptions.NO_OPTIONS));
1759 tempStr = XMPMetaFactory.serializeToString(stdXMP,keepItSmall);
1760 stdStr.append(tempStr);
1761 }
1762
1763 // Adjust the standard XMP padding to be up to 2KB.
1764
1765 assert ( (stdStr.length() > kTrailerLen) && (stdStr.length() <= kStdXMPLimit) );
1766
1767
1768 int extraPadding = kStdXMPLimit - stdStr.length(); // ! Do this before erasing the trailer.
1769 if ( extraPadding > 2047 ) extraPadding = 2047;
1770 stdStr.delete(stdStr.toString().indexOf(kPacketTrailer),stdStr.length());
1771
1772 for(int i = 0; i < extraPadding; ++i) {
1773 stdStr.append(' ');
1774 }
1775
1776 stdStr.append(kPacketTrailer).toString();
1777 }
1778
1779 /**
1780 * merges standard and extended XMP retrieved from a JPEG file.
1781 *
1782 * When an extended partition stores properties that do not fit into the
1783 * JPEG file limitation of 64K bytes, this function integrates those
1784 * properties back into the same XMP object with those from the standard XMP
1785 * packet.
1786 *
1787 * @param fullXMP
1788 * An XMP object which the caller has initialized from the
1789 * standard XMP packet in a JPEG file. The extended XMP is added
1790 * to this object.
1791 *
1792 * @param extendedXMP
1793 * An XMP object which the caller has initialized from the
1794 * extended XMP packet in a JPEG file.
1795 *
1796 * @throws XMPException
1797 * in case of internal error occurs.
1798 */
1799 public static void mergeFromJPEG ( XMPMeta fullXMP,
1800 XMPMeta extendedXMP ) throws XMPException
1801 {
1802
1803 TemplateOptions flags = new TemplateOptions(TemplateOptions.REPLACE_EXISTING_PROPERTIES |TemplateOptions.INCLUDE_INTERNAL_PROPERTIES);
1804 applyTemplate ( (XMPMetaImpl)fullXMP, (XMPMetaImpl)extendedXMP, flags );
1805 fullXMP.deleteProperty ( XMPConst.NS_XMP_NOTE, "HasExtendedXMP" );
1806
1807 }
1808
1809
1810 /**
1811 * modifies a working XMP object according to a template object.
1812 *
1813 * The XMP template can be used to add, replace or delete properties from
1814 * the working XMP object. The actions that you specify determine how the
1815 * template is applied. Each action can be applied individually or combined;
1816 * if you do not specify any actions, the properties and values in the
1817 * working XMP object do not change.
1818 *
1819 * @param OrigXMP
1820 * The destination XMP object.
1821 *
1822 * @param tempXMP
1823 * The template to apply to the destination XMP object.
1824 *
1825 * @param actions
1826 * Option flags to control the copying. If none are specified,
1827 * the properties and values in the working XMP do not change. A
1828 * logical OR of these bit-flag constants:
1829 * <ul>
1830 * <li><code> CLEAR_UNNAMED_PROPERTIES </code> Delete anything
1831 * that is not in the template.
1832 * <li><code> ADD_NEW_PROPERTIES </code> Add properties; see
1833 * detailed description.
1834 * <li><code> REPLACE_EXISTING_PROPERTIES </code> Replace the
1835 * values of existing properties.
1836 * <li><code> REPLACE_WITH_DELETE_EMPTY </code> Replace the
1837 * values of existing properties and delete properties if the new
1838 * value is empty.
1839 * <li><code> INCLUDE_INTERNAL_PROPERTIES </code> Operate on
1840 * internal properties as well as external properties.
1841 * </ul>
1842 *
1843 * @throws XMPException
1844 * in case of internal error occurs.
1845 */
1846
1847 static public void applyTemplate(XMPMeta OrigXMP, XMPMeta tempXMP, TemplateOptions actions) throws XMPException {
1848
1849 XMPMetaImpl workingXMP = (XMPMetaImpl) OrigXMP;
1850 XMPMetaImpl templateXMP = (XMPMetaImpl) tempXMP;
1851
1852 boolean doClear = (actions.getOptions() & TemplateOptions.CLEAR_UNNAMED_PROPERTIES) != 0;
1853 boolean doAdd = (actions.getOptions() & TemplateOptions.ADD_NEW_PROPERTIES) != 0;
1854 boolean doReplace = (actions.getOptions() & TemplateOptions.REPLACE_EXISTING_PROPERTIES) != 0;
1855
1856 boolean deleteEmpty = (actions.getOptions() & TemplateOptions.REPLACE_WITH_DELETE_EMPTY) != 0;
1857 doReplace |= deleteEmpty; // Delete-empty implies Replace.
1858 deleteEmpty &= (!doClear); // Clear implies not delete-empty, but keep
1859 // the implicit Replace.
1860
1861 boolean doAll = (actions.getOptions() & TemplateOptions.INCLUDE_INTERNAL_PROPERTIES) != 0;
1862
1863 // ! In several places we do loops backwards so that deletions do not
1864 // perturb the remaining indices.
1865 // ! These loops use ordinals (size .. 1), we must use a zero based
1866 // index inside the loop.
1867
1868 if (doClear) {
1869
1870 // Visit the top level working properties, delete if not in the
1871 // template.
1872
1873 for (int schemaOrdinal = workingXMP.getRoot().getChildrenLength(); schemaOrdinal > 0; --schemaOrdinal) {
1874 XMPNode workingSchema = workingXMP.getRoot().getChild(schemaOrdinal);
1875 XMPNode templateSchema = XMPNodeUtils.findSchemaNode(templateXMP.getRoot(), workingSchema.getName(),
1876 false);
1877
1878 if (templateSchema == null) {
1879
1880 // The schema is not in the template, delete all properties
1881 // or just all external ones.
1882
1883 if (doAll) {
1884 workingSchema.removeChildren(); // Remove the properties here, delete the schema below.
1885 } else {
1886 for (int propOrdinal = workingSchema.getChildrenLength(); propOrdinal > 0; --propOrdinal) {
1887 XMPNode workingProp = workingSchema.getChild(propOrdinal);
1888 if (!Utils.isInternalProperty(workingSchema.getName(), workingProp.getName())) {
1889 workingSchema.removeChild(propOrdinal);
1890 }
1891 }
1892 }
1893
1894 } else {
1895 // Check each of the working XMP's properties to see if it is in the template.
1896 for (int propOrdinal = workingSchema.getChildrenLength(); propOrdinal > 0; --propOrdinal) {
1897 XMPNode workingProp = workingSchema.getChild(propOrdinal);
1898 if ((doAll || !Utils.isInternalProperty(workingSchema.getName(), workingProp.getName()))
1899 && (XMPNodeUtils.findChildNode(templateSchema, workingProp.getName(), false) == null)) {
1900 workingSchema.removeChild(propOrdinal);
1901 }
1902 }
1903 }
1904 if (workingSchema.hasChildren() == false) {
1905 workingXMP.getRoot().removeChild(schemaOrdinal);
1906 }
1907 }
1908 }
1909
1910 if (doAdd | doReplace) {
1911
1912 for (int schemaNum = 0, schemaLim = templateXMP.getRoot()
1913 .getChildrenLength(); schemaNum < schemaLim; ++schemaNum) {
1914
1915 XMPNode templateSchema = templateXMP.getRoot().getChild(schemaNum + 1);
1916
1917 // Make sure we have an output schema node, then process the top level template properties.
1918
1919 XMPNode workingSchema = XMPNodeUtils.findSchemaNode(workingXMP.getRoot(), templateSchema.getName(),
1920 false);
1921 if (workingSchema == null) {
1922 workingSchema = new XMPNode(templateSchema.getName(), templateSchema.getValue(),
1923 new PropertyOptions(PropertyOptions.SCHEMA_NODE));
1924 workingXMP.getRoot().addChild(workingSchema);
1925 workingSchema.setParent(workingXMP.getRoot());
1926 }
1927
1928 for (int propNum = 1, propLim = templateSchema.getChildrenLength(); propNum <= propLim; ++propNum) {
1929 XMPNode templateProp = templateSchema.getChild(propNum);
1930 if (doAll || !Utils.isInternalProperty(templateSchema.getName(), templateProp.getName())) {
1931 appendSubtree(workingXMP, templateProp, workingSchema, doAdd, doReplace, deleteEmpty);
1932 }
1933 }
1934
1935 if (workingSchema.hasChildren() == false) {
1936 workingXMP.getRoot().removeChild(workingSchema);
1937 }
1938
1939 }
1940
1941 }
1942 }
1943
1944 }