SimpleXmpToJcrMetadataBuilder.java
60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.asset.api.Asset
* com.adobe.granite.asset.api.AssetMetadata
* com.adobe.xmp.XMPDateTime
* com.adobe.xmp.XMPDateTimeFactory
* com.adobe.xmp.XMPException
* com.adobe.xmp.XMPIterator
* com.adobe.xmp.XMPMeta
* com.adobe.xmp.XMPMetaFactory
* com.adobe.xmp.XMPPathFactory
* com.adobe.xmp.core.XMPException
* com.adobe.xmp.core.XMPMetadata
* com.adobe.xmp.core.parser.RDFXMLParser
* com.adobe.xmp.core.parser.RDFXMLParserContext
* com.adobe.xmp.options.PropertyOptions
* com.adobe.xmp.options.SerializeOptions
* com.adobe.xmp.properties.XMPProperty
* com.adobe.xmp.properties.XMPPropertyInfo
* com.adobe.xmp.schema.service.SchemaService
* com.day.cq.dam.api.Asset
* com.day.cq.dam.api.metadata.ExtractedMetadata
* com.day.cq.dam.api.metadata.xmp.XmpMappings
* javax.jcr.Binary
* javax.jcr.Item
* javax.jcr.NamespaceException
* javax.jcr.NamespaceRegistry
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.PathNotFoundException
* javax.jcr.Property
* javax.jcr.PropertyIterator
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Value
* javax.jcr.ValueFactory
* javax.jcr.Workspace
* org.apache.commons.imaging.common.RationalNumber
* org.apache.commons.io.IOUtils
* org.apache.commons.lang.StringUtils
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Property
* org.apache.jackrabbit.util.Text
* org.apache.sling.api.resource.Resource
* org.apache.sling.commons.osgi.PropertiesUtil
* org.osgi.service.component.ComponentContext
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.dam.commons.metadata;
import com.adobe.granite.asset.api.AssetMetadata;
import com.adobe.xmp.XMPDateTime;
import com.adobe.xmp.XMPDateTimeFactory;
import com.adobe.xmp.XMPException;
import com.adobe.xmp.XMPIterator;
import com.adobe.xmp.XMPMeta;
import com.adobe.xmp.XMPMetaFactory;
import com.adobe.xmp.XMPPathFactory;
import com.adobe.xmp.core.XMPMetadata;
import com.adobe.xmp.core.parser.RDFXMLParser;
import com.adobe.xmp.core.parser.RDFXMLParserContext;
import com.adobe.xmp.options.PropertyOptions;
import com.adobe.xmp.options.SerializeOptions;
import com.adobe.xmp.properties.XMPProperty;
import com.adobe.xmp.properties.XMPPropertyInfo;
import com.adobe.xmp.schema.service.SchemaService;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.metadata.ExtractedMetadata;
import com.day.cq.dam.api.metadata.xmp.XmpMappings;
import com.day.cq.dam.commons.util.DateParser;
import com.day.cq.dam.commons.xml.DocumentBuilderFactoryProvider;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Binary;
import javax.jcr.Item;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.imaging.common.RationalNumber;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
@Component(metatype=1, label="SimpleXmpToJcrMetadataBuilder Handler", description="SimpleXmpToJcrMetadataBuilder Handler")
public class SimpleXmpToJcrMetadataBuilder {
private static final String XMP_ARRAY_TYPE = "xmpArrayType";
private static final String IS_XMP_ARRAY = "isXMPArray";
private static final Logger log = LoggerFactory.getLogger(SimpleXmpToJcrMetadataBuilder.class);
public static final String NT_RDF_BAG = "rdf:Bag";
public static final String NT_RDF_SEQ = "rdf:Seq";
public static final String NT_RDF_ALT = "rdf:Alt";
private static final String INGREDIENT_TAG = "xmpMM:Ingredients";
private static final String SYNC_FLAG = "newRendition";
private static final String DAM_NS_URI = "http://www.day.com/dam/1.0";
private static final int DEFAULT_FILTER_LIMIT_FOR_XMP = 100;
@org.apache.felix.scr.annotations.Property(intValue={100}, label="Limit for XMP Filtering", description="Maximum number of nodes that can be parsed/stored for xmp properties configured here")
private static final String FILTER_LIMIT_FOR_XMP = "xmp.filterlimit";
private static final String DOC_ANCESTOR = "photoshop:DocumentAncestors";
private static final String[] DEFAULT_XMP_FILTER_PROPERTIES = new String[]{"photoshop:DocumentAncestors"};
@org.apache.felix.scr.annotations.Property(value={"photoshop:DocumentAncestors"}, cardinality=2, label="XMP Properties to be Filtered", description="XMP Properties to be Filtered")
private static final String XMP_PROPERTIES_FILTER = "xmp.filterproperties";
private static int filterLimit;
private static String[] filteredXMPProperties;
private String[] defaultFormats = new String[]{"application/octet-stream"};
private static final List<String> altArrayProps;
private static final List<String> ignoreHierarchy;
public final Map<String, String> conflictPropMap = new HashMap<String, String>(5);
@Activate
private void activate(ComponentContext ctx) {
Dictionary cfg = ctx.getProperties();
filterLimit = PropertiesUtil.toInteger(cfg.get("xmp.filterlimit"), (int)100);
filteredXMPProperties = PropertiesUtil.toStringArray(cfg.get("xmp.filterproperties"), (String[])DEFAULT_XMP_FILTER_PROPERTIES);
}
public SimpleXmpToJcrMetadataBuilder() {
this.conflictPropMap.put("ImageLength", "Image Length");
this.conflictPropMap.put("ImageWidth", "Image Width");
this.conflictPropMap.put("tiff:ImageWidth", "Image Width");
this.conflictPropMap.put("tiff:ImageLength", "Image Length");
this.conflictPropMap.put("dc:description", "description");
this.conflictPropMap.put("dc:description", "Caption/Abstract");
}
@Deprecated
public void storeXmp(Node metadataRoot, XMPMeta meta, boolean doSave) throws XMPException, RepositoryException {
String rootPath;
XMPIterator itr = meta.iterator();
String parent = rootPath = metadataRoot.getPath();
HashMap<String, List<XMPPropertyInfo>> arrayMap = new HashMap<String, List<XMPPropertyInfo>>();
while (itr.hasNext()) {
String path;
XMPPropertyInfo prop = (XMPPropertyInfo)itr.next();
if (prop.getOptions().isSchemaNode()) continue;
if (prop.getOptions().isQualifier() || prop.getOptions().isSimple()) {
this.checkNamespace(prop, metadataRoot);
String string = path = Text.getRelativeParent((String)prop.getPath(), (int)1).equals("") ? parent : parent + "/" + Text.getRelativeParent((String)prop.getPath(), (int)1);
if (this.isArrayMember(arrayMap, prop.getPath())) {
if (prop.getOptions().isQualifier()) {
log.debug("Qualifier detected (noop): " + prop.toString());
continue;
}
if (prop.getOriValue() == null) continue;
String p = prop.getPath();
p = p.substring(0, p.lastIndexOf("["));
arrayMap.get(p).add(prop);
continue;
}
if (prop.getOptions().isQualifier()) {
log.debug("Qualifier detected (noop): " + prop.toString());
continue;
}
if (prop.getOriValue() != null) {
Node node = this.getOrCreateNode(metadataRoot.getSession(), path, "nt:unstructured");
if (node != null) {
this.setProperty(node, prop);
}
log.debug("PATH: " + parent + "/" + prop.getPath() + ":" + prop.getValue());
continue;
}
log.debug(prop.getPath() + " is NULL");
continue;
}
if (prop.getOptions().isArray()) {
this.checkNamespace(prop, metadataRoot);
ArrayList<XMPPropertyInfo> members = new ArrayList<XMPPropertyInfo>();
members.add(prop);
arrayMap.put(prop.getPath(), members);
continue;
}
if (!prop.getOptions().isStruct()) continue;
if (this.isArrayMember(arrayMap, prop.getPath())) {
log.debug("Struct as member of array");
if (prop.getOptions().isQualifier()) {
log.debug("Qualifier detected (noop): " + prop.toString());
continue;
}
if (prop.getOriValue() == null) continue;
String p = prop.getPath();
int arrayIndexStrt = p.lastIndexOf("[");
if (arrayIndexStrt > -1) {
p = p.substring(0, arrayIndexStrt);
}
arrayMap.get(p).add(prop);
continue;
}
this.checkNamespace(prop, metadataRoot);
path = parent + "/" + prop.getPath();
this.getOrCreateNode(metadataRoot.getSession(), path, "nt:unstructured");
}
for (String path : arrayMap.keySet()) {
Node node;
String parentPath = Text.getRelativeParent((String)path, (int)1);
List arrayMembers = (List)arrayMap.get(path);
if (arrayMembers.size() <= 1 || (node = this.getOrCreateNode(metadataRoot.getSession(), rootPath + "/" + this.normalizeArrayPath(parentPath), "nt:unstructured")) == null) continue;
XMPPropertyInfo arrayProp = (XMPPropertyInfo)arrayMembers.remove(0);
String name = "rdf:Bag";
if (arrayProp.getOptions().isArrayOrdered()) {
name = "rdf:Seq";
} else if (arrayProp.getOptions().isArrayAlternate()) {
name = "rdf:Alt";
}
XMPPropertyInfo firstMember = (XMPPropertyInfo)arrayMembers.get(0);
if (firstMember.getOptions().isStruct() && !"xmpMM:Ingredients".equalsIgnoreCase(Text.getName((String)path))) {
Node arrayNode = this.getOrCreateNode(metadataRoot.getSession(), node.getPath() + "/" + Text.getName((String)path), "nt:unstructured");
arrayNode.setProperty("xmpArrayType", name);
arrayNode.setProperty("isXMPArray", true);
NodeIterator nodes = arrayNode.getNodes();
while (nodes.hasNext()) {
Node childNode = (Node)nodes.next();
childNode.remove();
}
for (XMPPropertyInfo prop : arrayMembers) {
if (prop.getOptions().isStruct()) {
this.getOrCreateNode(metadataRoot.getSession(), rootPath + "/" + this.normalizeArrayPath(prop.getPath()), "nt:unstructured");
continue;
}
if (!prop.getOptions().isSimple()) continue;
String parentStructPath = Text.getRelativeParent((String)prop.getPath(), (int)1);
Node parentStructNode = this.getOrCreateNode(metadataRoot.getSession(), rootPath + "/" + this.normalizeArrayPath(parentStructPath), "nt:unstructured");
this.setProperty(parentStructNode, prop);
}
continue;
}
this.setMvProperty(node, arrayMembers, Text.getName((String)path));
}
if (doSave) {
metadataRoot.getSession().save();
}
}
private String normalizeArrayPath(String xmpPath) {
xmpPath = xmpPath.replace("[", "/");
return xmpPath.replace("]", "");
}
public void storeXmp(Node metadataRoot, XMPMeta meta) throws XMPException, RepositoryException {
this.storeXmp(metadataRoot, meta, true);
}
private boolean isArrayMember(Map<String, List<XMPPropertyInfo>> arrayMap, String path) {
if (path.lastIndexOf("[") > 0) {
String parentPath = path.substring(0, path.lastIndexOf("["));
return arrayMap.containsKey(parentPath);
}
return false;
}
@Deprecated
public XMPMeta getXmpFromJcr(Node metadataRoot) throws RepositoryException, XMPException {
XMPMeta meta = XMPMetaFactory.create();
PropertyIterator props = metadataRoot.getProperties();
while (props.hasNext()) {
try {
String namespace;
Property prop = props.nextProperty();
String name = prop.getName();
if (name.indexOf(":") < 0) {
log.debug("property [{}] doesn't have namespace prefix, skipping. metadata node: [{}].", (Object)name, (Object)metadataRoot.getPath());
continue;
}
String[] splits = name.split(":");
String nsPrefix = splits[0];
String regPrefix = this.registerNs(nsPrefix, namespace = metadataRoot.getSession().getWorkspace().getNamespaceRegistry().getURI(nsPrefix));
if (!regPrefix.equals(nsPrefix) && splits.length > 1) {
nsPrefix = regPrefix;
name = nsPrefix + ":" + splits[1];
}
if (name.indexOf("jcr:") < 0 && !prop.isMultiple()) {
Object val = this.getValue(prop);
try {
this.registerNs(nsPrefix, namespace);
if (altArrayProps.contains(name) && val instanceof String) {
meta.setLocalizedText(namespace, name, "x-default", "x-default", (String)val);
continue;
}
meta.setProperty(namespace, name, val);
}
catch (XMPException xmpe) {
if (log.isDebugEnabled()) {
log.debug("Cannot set xmp property: " + xmpe.getMessage(), (Throwable)xmpe);
continue;
}
log.warn("Cannot set xmp property: " + xmpe.getMessage());
}
continue;
}
if (name.indexOf("jcr:") >= 0 || !prop.isMultiple()) continue;
Object[] vals = this.getMultiValues(prop);
try {
this.registerNs(nsPrefix, namespace);
if (altArrayProps.contains(name) && vals.length == 1) {
if (!(vals[0] instanceof String)) continue;
meta.setLocalizedText(namespace, name, "x-default", "x-default", (String)vals[0]);
continue;
}
for (Object v : vals) {
if (!(v instanceof String)) continue;
meta.appendArrayItem(namespace, name, new PropertyOptions().setArray(true), (String)v, null);
}
continue;
}
catch (XMPException xmpe) {
if (log.isDebugEnabled()) {
log.debug("Cannot set xmp property: " + xmpe.getMessage(), (Throwable)xmpe);
continue;
}
log.warn("Cannot set xmp property: " + xmpe.getMessage());
}
}
catch (RepositoryException re) {
log.error("Cannot set xmp property: " + re.getMessage(), (Throwable)re);
}
}
try {
this.checkForComplexMetadata(metadataRoot, meta, null, null, new HashMap<String, PropertyOptions>());
}
catch (PathNotFoundException e) {
log.info("Complex Metadata extraction is not applicable for the binary");
}
catch (Exception e) {
log.error("Unable to extract the complex metadata " + e.getMessage(), (Throwable)e);
}
return meta;
}
private void checkForComplexMetadata(Node metadataRoot, XMPMeta xmpMeta, String nodeName, String nsRootURI, Map<String, PropertyOptions> arrOfStructMap) throws XMPException, RepositoryException {
String pNodeName = nodeName;
NodeIterator iter = metadataRoot.getNodes();
while (iter.hasNext()) {
String childRootURI = nsRootURI;
Node childMetadataNode = iter.nextNode();
PropertyIterator dpi = childMetadataNode.getProperties();
PropertyOptions dpropertyOption = new PropertyOptions();
dpropertyOption.setArray(true);
String string = nodeName = pNodeName == null ? childMetadataNode.getName() : pNodeName + "/" + childMetadataNode.getName();
if (childRootURI == null) {
if (childMetadataNode.getName().indexOf(":") < 0) {
log.warn("property [{}] doesn't have namespace prefix, skipping. metadata node: [{}].", (Object)childMetadataNode.getName(), (Object)childMetadataNode.getPath());
return;
}
childRootURI = this.registerPrefix((Item)childMetadataNode);
}
if (childMetadataNode.hasProperty("isXMPArray") || childMetadataNode.hasProperty("xmpNodeType") && "xmpArray".equals(childMetadataNode.getProperty("xmpNodeType").getString())) {
PropertyOptions arrayOptions = new PropertyOptions();
if (childMetadataNode.hasProperty("xmpArrayType")) {
String arrayType = childMetadataNode.getProperty("xmpArrayType").getString();
if ("rdf:Bag".equals(arrayType)) {
arrayOptions.setArray(true);
} else if ("rdf:Seq".equals(arrayType)) {
arrayOptions.setArrayOrdered(true);
} else if ("rdf:Alt".equals(arrayType)) {
arrayOptions.setArrayAlternate(true);
}
} else {
arrayOptions.setArray(true);
}
arrOfStructMap.put(childMetadataNode.getPath(), arrayOptions);
} else {
if (arrOfStructMap.containsKey(metadataRoot.getPath())) {
xmpMeta.appendArrayItem(childRootURI, pNodeName, arrOfStructMap.get(metadataRoot.getPath()), null, new PropertyOptions().setStruct(true));
int index = xmpMeta.countArrayItems(childRootURI, pNodeName);
nodeName = pNodeName + "[" + index + "]";
}
while (dpi.hasNext()) {
Property p = dpi.nextProperty();
if (p.getName().indexOf(":") < 0) {
log.debug("property [{}] doesn't have namespace prefix, skipping. metadata node: [{}].", (Object)p.getName(), (Object)childMetadataNode.getPath());
continue;
}
this.registerPrefix((Item)p);
if (childRootURI == null || p.getName() == null) continue;
if (p.getName().indexOf("jcr:") < 0 && p.isMultiple()) {
log.debug("Multiple value metadata property {}, creating String[] in XMP", (Object)p.getName());
try {
Value[] values;
for (Value value : values = p.getValues()) {
xmpMeta.appendArrayItem(childRootURI, nodeName + "/" + p.getName(), dpropertyOption, value.getString(), null);
}
continue;
}
catch (XMPException xmpe) {
if (log.isDebugEnabled()) {
log.debug("Cannot set xmp property: " + xmpe.getMessage(), (Throwable)xmpe);
continue;
}
log.warn("Cannot set xmp property: " + xmpe.getMessage());
continue;
}
}
if (p.getName().indexOf("jcr:") >= 0 || p.isMultiple()) continue;
log.debug("Writing {} with value: {}", (Object)p.getName(), (Object)p.getString());
try {
xmpMeta.setProperty(childRootURI, nodeName + "/" + p.getName(), (Object)p.getString());
}
catch (XMPException xmpe) {
if (log.isDebugEnabled()) {
log.debug("Cannot set xmp property: " + xmpe.getMessage(), (Throwable)xmpe);
continue;
}
log.warn("Cannot set xmp property: " + xmpe.getMessage());
}
}
}
if (childMetadataNode.getNodes().getSize() <= 0) continue;
this.checkForComplexMetadata(childMetadataNode, xmpMeta, nodeName, childRootURI, arrOfStructMap);
}
}
private String registerPrefix(Item jcrItem) throws RepositoryException {
String childPrefix = jcrItem.getName().substring(0, jcrItem.getName().indexOf(":"));
String nsUriChild = jcrItem.getSession().getWorkspace().getNamespaceRegistry().getURI(childPrefix);
try {
this.registerNs(childPrefix, nsUriChild);
}
catch (XMPException xmpe) {
log.warn("Cannot process the xmp structure: " + xmpe.getMessage());
}
return nsUriChild;
}
@Deprecated
public void storeAsXmp(ExtractedMetadata metadata, Node metadataRoot, boolean doSave) throws XMPException, RepositoryException {
XMPMeta meta = XMPMetaFactory.create();
this.convertToXmp(metadata, metadataRoot, meta, doSave);
this.storeXmp(metadataRoot, meta, doSave);
}
private InputStream filterXMPProperties(InputStream xmpIS) {
ByteArrayOutputStream baos;
block23 : {
DocumentBuilder builder;
Document xmpXmlDocument = null;
if (xmpIS.markSupported()) {
xmpIS.mark(20971520);
}
try {
builder = new DocumentBuilderFactoryProvider().createSecureBuilderFactory(false).newDocumentBuilder();
}
catch (ParserConfigurationException e) {
return xmpIS;
}
try {
xmpXmlDocument = builder.parse(xmpIS);
}
catch (SAXException e) {
if (xmpIS.markSupported()) {
try {
xmpIS.reset();
}
catch (Exception ignore) {
log.warn("Failed to parse XMP XML, metadata info may not be correct");
}
}
return xmpIS;
}
catch (IOException e) {
if (xmpIS.markSupported()) {
try {
xmpIS.reset();
}
catch (Exception ignore) {
log.warn("Failed to parse XMP XML, metadata info may not be correct");
}
}
return xmpIS;
}
for (String xmpNodeTagName : filteredXMPProperties) {
int xmpFilterNodeIdx;
NodeList xmpFilterNode = xmpXmlDocument.getElementsByTagName(xmpNodeTagName);
int xmpFilterNodeCount = xmpFilterNode.getLength();
int totalParsedXMPFilterNode = 0;
org.w3c.dom.Node xmpFilterNodeItem = null;
org.w3c.dom.Node xmpFilterNodeItemList = null;
for (xmpFilterNodeIdx = 0; xmpFilterNodeIdx < xmpFilterNodeCount && totalParsedXMPFilterNode < filterLimit; ++xmpFilterNodeIdx) {
xmpFilterNodeItemList = xmpFilterNode.item(xmpFilterNodeIdx).getFirstChild();
while (xmpFilterNodeItemList.getNodeType() != 1) {
xmpFilterNodeItemList = xmpFilterNodeItemList.getNextSibling();
}
for (xmpFilterNodeItem = xmpFilterNodeItemList.getFirstChild(); totalParsedXMPFilterNode < filterLimit && xmpFilterNodeItem != null; xmpFilterNodeItem = xmpFilterNodeItem.getNextSibling()) {
if (xmpFilterNodeItem.getNodeType() != 1) continue;
++totalParsedXMPFilterNode;
}
}
if (xmpFilterNodeItem != null) {
org.w3c.dom.Node xmpFilterNodeItemNext = xmpFilterNodeItem.getNextSibling();
while (xmpFilterNodeItemNext != null) {
xmpFilterNodeItemNext.getParentNode().removeChild(xmpFilterNodeItem);
xmpFilterNodeItem = xmpFilterNodeItemNext;
xmpFilterNodeItemNext = xmpFilterNodeItem.getNextSibling();
}
}
while (xmpFilterNodeIdx < xmpFilterNodeCount) {
xmpFilterNode.item(xmpFilterNodeCount - 1).getParentNode().removeChild(xmpFilterNode.item(xmpFilterNodeCount - 1));
--xmpFilterNodeCount;
}
}
baos = new ByteArrayOutputStream();
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(xmpXmlDocument);
StreamResult result = new StreamResult(baos);
transformer.transform(source, result);
}
catch (Exception ign) {
if (!xmpIS.markSupported()) break block23;
try {
xmpIS.reset();
return xmpIS;
}
catch (IOException ignore) {
log.warn("Failed to parse XMP XML, metadata info may not be correct");
}
}
}
return new ByteArrayInputStream(baos.toByteArray());
}
public void storeAsXmp(ExtractedMetadata metadata, Asset asset, boolean doSave) throws XMPException, RepositoryException {
Node assetNode = (Node)asset.adaptTo(Node.class);
Node metadataRoot = assetNode.getNode("jcr:content/metadata");
InputStream is = metadata.getXmp();
XMPMeta xmpMeta = null;
try {
if (is != null) {
is = this.filterXMPProperties(is);
xmpMeta = XMPMetaFactory.parse((InputStream)is);
this.resolvePropConflict(metadata, this.conflictPropMap);
this.resolvePropConflict(metadata, xmpMeta, this.conflictPropMap);
this.convertToXmp(metadata, metadataRoot, xmpMeta, doSave);
if (metadataRoot.hasProperty("dc:format") && !this.isDefaultFormat(metadataRoot.getProperty("dc:format").getValue().getString()) && xmpMeta.getPropertyString("http://purl.org/dc/elements/1.1/", "dc:format") != null) {
xmpMeta.deleteProperty("http://purl.org/dc/elements/1.1/", "dc:format");
}
} else {
xmpMeta = XMPMetaFactory.create();
this.convertToXmp(metadata, metadataRoot, xmpMeta, doSave);
}
XMPMetadata xmpMetadata = null;
byte[] xmpBytes = XMPMetaFactory.serializeToBuffer((XMPMeta)xmpMeta, (SerializeOptions)null);
RDFXMLParserContext parserContext = new RDFXMLParserContext();
xmpMetadata = new RDFXMLParser().parse(xmpBytes, (Map)parserContext);
Set nss = parserContext.getPrefixDefinitions().keySet();
for (String ns : nss) {
this.checkNamespace((String)parserContext.getPrefixDefinitions().get(ns), metadataRoot);
}
AssetMetadata assetMetadata = ((com.adobe.granite.asset.api.Asset)((Resource)asset.adaptTo(Resource.class)).adaptTo(com.adobe.granite.asset.api.Asset.class)).getAssetMetadata();
assetMetadata.setXMP(xmpMetadata, null, ignoreHierarchy);
}
catch (com.adobe.xmp.core.XMPException e) {
log.info("cannot convert extractedmetadata to XMPMetadata", (Throwable)e);
}
}
private boolean isDefaultFormat(String format) {
for (int i = 0; i < this.defaultFormats.length; ++i) {
if (!this.defaultFormats[i].equals(format)) continue;
return true;
}
return false;
}
private void convertToXmp(ExtractedMetadata metadata, Node metadataRoot, XMPMeta meta, boolean doSave) throws XMPException, RepositoryException {
Set keys = metadata.getMetaDataProperties().keySet();
for (String mkey : keys) {
String[] xmpKeys;
String key = mkey.replaceAll("\\(", "").replaceAll("\\)", "");
if (XmpMappings.defaultSimpleXmpMappings.containsKey(key)) {
for (String xmpKey : xmpKeys = this.getXmpKeys((String)XmpMappings.defaultSimpleXmpMappings.get(key))) {
try {
this.setXmpProperty(meta, xmpKey, metadata.getMetaDataProperties().get(key), metadataRoot.getSession());
continue;
}
catch (XMPException e) {
log.debug("Cannot create xmp property: " + e.getMessage(), (Throwable)e);
}
}
continue;
}
if (XmpMappings.defaultBagXmpMappings.containsKey(key) || XmpMappings.defaultSeqXmpMappings.containsKey(key) || XmpMappings.defaultAltXmpMappings.containsKey(key)) {
xmpKeys = new String[]{};
if (XmpMappings.defaultBagXmpMappings.containsKey(key)) {
xmpKeys = this.getXmpKeys((String)XmpMappings.defaultBagXmpMappings.get(key));
} else if (XmpMappings.defaultSeqXmpMappings.containsKey(key)) {
xmpKeys = this.getXmpKeys((String)XmpMappings.defaultSeqXmpMappings.get(key));
} else if (XmpMappings.defaultAltXmpMappings.containsKey(key)) {
xmpKeys = this.getXmpKeys((String)XmpMappings.defaultAltXmpMappings.get(key));
}
for (String xmpKey : xmpKeys) {
try {
String namespace = this.getNamespace(xmpKey);
Object val = metadata.getMetaDataProperties().get(key);
if (val instanceof List) {
List valList = (List)val;
for (Object value : valList) {
boolean exists = SimpleXmpToJcrMetadataBuilder.doesArrayItemExistInXMPMeta(meta, namespace, xmpKey, (String)value);
if (exists) continue;
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), (String)value, null);
}
continue;
}
if (val instanceof Object[]) {
Object[] valArray;
for (Object value : valArray = (Object[])val) {
boolean exists = SimpleXmpToJcrMetadataBuilder.doesArrayItemExistInXMPMeta(meta, namespace, xmpKey, value.toString());
if (exists) continue;
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), value.toString(), null);
}
continue;
}
if (val.getClass().isArray() && val.getClass().getComponentType().isPrimitive()) {
Class componentType = val.getClass().getComponentType();
if (Boolean.TYPE.isAssignableFrom(componentType)) {
for (Object value : (boolean[])val) {
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), "" + (boolean)value + "", null);
}
continue;
}
if (Float.TYPE.isAssignableFrom(componentType)) {
for (Object value : (float[])val) {
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), "" + (float)value + "", null);
}
continue;
}
if (Double.TYPE.isAssignableFrom(componentType)) {
for (Object value : (double[])val) {
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), "" + (double)value + "", null);
}
continue;
}
if (Integer.TYPE.isAssignableFrom(componentType)) {
for (Object value : (int[])val) {
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), "" + (int)value + "", null);
}
continue;
}
if (Long.TYPE.isAssignableFrom(componentType)) {
for (Object value : (long[])val) {
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), "" + (long)value + "", null);
}
continue;
}
if (!Short.TYPE.isAssignableFrom(componentType)) continue;
for (Object value : (short[])val) {
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), "" + (int)value + "", null);
}
continue;
}
String strVal = val instanceof String ? (String)val : String.valueOf(val);
boolean exists = SimpleXmpToJcrMetadataBuilder.doesArrayItemExistInXMPMeta(meta, namespace, xmpKey, strVal);
if (exists) continue;
meta.appendArrayItem(namespace, xmpKey, new PropertyOptions().setArray(true), strVal, null);
continue;
}
catch (XMPException e) {
log.debug("Cannot create xmp property: " + e.getMessage());
}
}
continue;
}
if (key.indexOf(":") < 0) {
String nsPrefix = this.registerNs("dam", "http://www.day.com/dam/1.0");
try {
Object value = metadata.getMetaDataProperties().get(key);
String xmpKey = nsPrefix + ":" + key.replace(" ", "");
if (value instanceof List) {
List valList = (List)value;
for (Object val : valList) {
boolean exists = SimpleXmpToJcrMetadataBuilder.doesArrayItemExistInXMPMeta(meta, "http://www.day.com/dam/1.0", xmpKey, (String)val);
if (exists) continue;
meta.appendArrayItem("http://www.day.com/dam/1.0", xmpKey, new PropertyOptions().setArray(true), (String)val, null);
}
continue;
}
if (value instanceof Object[]) {
Object[] valArray;
for (Object val : valArray = (Object[])value) {
boolean exists = SimpleXmpToJcrMetadataBuilder.doesArrayItemExistInXMPMeta(meta, "http://www.day.com/dam/1.0", xmpKey, val.toString());
if (exists) continue;
meta.appendArrayItem("http://www.day.com/dam/1.0", xmpKey, new PropertyOptions().setArray(true), val.toString(), null);
}
continue;
}
if (value == null || value instanceof String && StringUtils.isEmpty((String)((String)value))) continue;
meta.setProperty("http://www.day.com/dam/1.0", xmpKey.trim(), value);
}
catch (XMPException e) {
if (log.isDebugEnabled()) {
log.debug("Cannot set xmp property:" + e.getMessage(), (Throwable)e);
continue;
}
log.warn("Cannot set xmp property:" + e.getMessage());
}
continue;
}
try {
this.setXmpProperty(meta, key, metadata.getMetaDataProperties().get(key), metadataRoot.getSession());
}
catch (XMPException e) {
log.debug("Cannot create xmp property: " + e.getMessage());
}
}
}
public void storeAsXmp(ExtractedMetadata metadata, Node metadataRoot) throws XMPException, RepositoryException {
this.storeAsXmp(metadata, metadataRoot, true);
}
private void setXmpProperty(XMPMeta meta, String xmpKey, Object value, Session session) throws XMPException, RepositoryException {
if (value != null) {
try {
String nsPrefix = xmpKey.substring(0, xmpKey.indexOf(":"));
String nsUri = session.getNamespaceURI(nsPrefix);
nsPrefix = this.registerNs(nsPrefix, nsUri);
if (value instanceof Boolean) {
meta.setPropertyBoolean(nsUri, xmpKey, ((Boolean)value).booleanValue());
} else if (value instanceof Calendar) {
meta.setPropertyCalendar(nsUri, xmpKey, (Calendar)value);
} else if (value instanceof Date) {
Calendar cal = Calendar.getInstance();
cal.setTime((Date)value);
meta.setPropertyDate(nsUri, xmpKey, XMPDateTimeFactory.createFromCalendar((Calendar)cal));
} else if (value instanceof Double) {
meta.setPropertyDouble(nsUri, xmpKey, ((Double)value).doubleValue());
} else if (value instanceof Integer) {
meta.setPropertyInteger(nsUri, xmpKey, ((Integer)value).intValue());
} else if (value instanceof Long) {
meta.setPropertyLong(nsUri, xmpKey, ((Long)value).longValue());
} else if (value instanceof String) {
if (!StringUtils.isEmpty((String)((String)value))) {
meta.setProperty(nsUri, xmpKey, value);
}
} else if (value instanceof List) {
List valList = (List)value;
for (Object val : valList) {
boolean exists = SimpleXmpToJcrMetadataBuilder.doesArrayItemExistInXMPMeta(meta, nsUri, xmpKey, (String)val);
if (exists) continue;
meta.appendArrayItem(nsUri, xmpKey, new PropertyOptions().setArray(true), (String)val, null);
}
} else {
meta.setProperty(nsUri, xmpKey, value);
}
}
catch (NamespaceException nsEx) {
if (log.isDebugEnabled()) {
log.debug("namespace exception in setting xmp property", (Throwable)nsEx);
}
log.warn("namespace exception in setting xmp property", (Object)nsEx.getMessage());
}
}
}
private String[] getXmpKeys(String keyString) {
if (keyString.indexOf(",") > 0) {
return keyString.split(",");
}
return new String[]{keyString};
}
private String getNamespace(String xmpKey) {
if (xmpKey.indexOf(":") > 0) {
String nsPrefix = xmpKey.substring(0, xmpKey.indexOf(":"));
return XMPMetaFactory.getSchemaRegistry().getNamespaceURI(nsPrefix);
}
return null;
}
private Node getOrCreateNode(Session session, String path, String nodetype) {
block5 : {
try {
if (session.itemExists(path)) {
return (Node)session.getItem(path);
}
Node childMetaNode = session.getRootNode().addNode(path.substring(1), nodetype);
childMetaNode.setProperty("newRendition", true);
return childMetaNode;
}
catch (RepositoryException e) {
log.warn("Failed to get or create node {}", (Object)path, (Object)e.getMessage());
if (log.isDebugEnabled()) {
log.debug("Failed to get or create node", (Throwable)e);
}
}
catch (Exception e) {
if (!log.isDebugEnabled()) break block5;
log.debug("Failed to get or create node", (Throwable)e);
}
}
return null;
}
private String getPropertyName(Node node, XMPPropertyInfo prop) {
String name;
String path = prop.getPath();
String string = name = path.lastIndexOf("/") > 0 ? path.substring(path.lastIndexOf("/") + 1) : path;
if (name.indexOf(":") > 0) {
String[] splits = name.split(":");
String prefix = splits[0];
String namespace = XMPMetaFactory.getSchemaRegistry().getNamespaceURI(prefix);
if (namespace != null) {
try {
String regPrefix = this.checkNamespace(namespace, node);
if (!regPrefix.equals(prefix)) {
prefix = regPrefix;
}
}
catch (RepositoryException e) {
log.warn("Failed to check the namespace {}", (Object)namespace);
}
if (splits.length > 1) {
name = prefix + ":" + Text.escapeIllegalJcrChars((String)splits[1]);
}
} else {
name = Text.escapeIllegalJcrChars((String)name);
}
} else {
name = Text.escapeIllegalJcrChars((String)name);
}
return name;
}
private static boolean doesArrayItemExistInXMPMeta(XMPMeta meta, String schemaNS, String arrayName, String itemValue) {
try {
int numOfItems = meta.countArrayItems(schemaNS, arrayName);
for (int index = 1; index <= numOfItems; ++index) {
String propPath = XMPPathFactory.composeArrayItemPath((String)arrayName, (int)index);
String property = meta.getPropertyString(schemaNS, propPath);
if (property == null || !property.equals(itemValue)) continue;
return true;
}
}
catch (XMPException e) {
return false;
}
return false;
}
private void resolvePropConflict(ExtractedMetadata metadata, Map<String, String> conflictPropMap) {
for (Map.Entry<String, String> entry : conflictPropMap.entrySet()) {
if (!metadata.getMetaDataProperties().containsKey(entry.getKey()) || !metadata.getMetaDataProperties().containsKey(entry.getValue())) continue;
metadata.getMetaDataProperties().remove(entry.getKey());
}
}
private void resolvePropConflict(ExtractedMetadata metadata, XMPMeta meta, Map<String, String> conflictPropMap) {
for (Map.Entry<String, String> entry : conflictPropMap.entrySet()) {
try {
String namespace = this.getNamespace(entry.getKey());
if (namespace != null) {
XMPProperty property = meta.getProperty(namespace, entry.getKey());
if (property == null || !metadata.getMetaDataProperties().containsKey(entry.getValue())) continue;
meta.deleteProperty(namespace, entry.getKey());
continue;
}
log.debug("namespace is null {} ", (Object)entry.getKey());
}
catch (XMPException e) {
log.debug("exception while getting the property", (Throwable)e);
}
}
}
private Property setProperty(Node node, XMPPropertyInfo prop) {
Property p = null;
try {
Object val = prop.getOriValue();
String name = this.getPropertyName(node, prop);
val = this.checkForDate(val);
val = this.checkExif(name, val);
if (val instanceof Boolean) {
p = node.setProperty(name, ((Boolean)val).booleanValue());
} else if (val instanceof Long || val instanceof Integer) {
p = node.setProperty(name, val instanceof Long ? (Long)val : (long)((Integer)val).intValue());
} else if (val instanceof Short) {
p = node.setProperty(name, (long)((Short)val).shortValue());
} else if (val instanceof Double) {
Double value = (Double)val;
p = node.setProperty(name, value.isInfinite() || value.isNaN() ? 0.0 : value);
} else if (val instanceof XMPDateTime) {
p = node.setProperty(name, ((XMPDateTime)val).getCalendar());
} else if (val instanceof byte[]) {
p = node.setProperty(name, node.getSession().getValueFactory().createBinary((InputStream)new ByteArrayInputStream((byte[])val)));
} else if (val instanceof Byte) {
p = node.setProperty(name, (long)((Byte)val).intValue());
} else if (val instanceof Date) {
Calendar cal = Calendar.getInstance();
cal.setTime((Date)val);
p = node.setProperty(name, cal);
} else if (val instanceof Calendar) {
p = node.setProperty(name, (Calendar)val);
} else if (val instanceof RationalNumber) {
double doubleVal = ((RationalNumber)val).doubleValue();
Double value = doubleVal;
p = node.setProperty(name, value.isInfinite() || value.isNaN() ? 0.0 : value);
} else if (val instanceof RationalNumber[]) {
ArrayList<Value> vals = new ArrayList<Value>();
RationalNumber[] arr$ = (RationalNumber[])val;
int len$ = arr$.length;
for (int i$ = 0; i$ < len$; ++i$) {
RationalNumber rv;
Double value;
double doubleVal;
vals.add(node.getSession().getValueFactory().createValue((value = Double.valueOf(doubleVal = (rv = arr$[i$]).doubleValue())).isInfinite() || value.isNaN() ? 0.0 : value));
}
p = node.setProperty(name, vals.toArray((T[])new Value[vals.size()]));
} else if (val instanceof int[]) {
ArrayList<Value> vals = new ArrayList<Value>();
int[] arr$ = (int[])val;
int len$ = arr$.length;
for (int i$ = 0; i$ < len$; ++i$) {
Integer i = arr$[i$];
vals.add(node.getSession().getValueFactory().createValue((long)i.intValue()));
}
p = node.setProperty(name, vals.toArray((T[])new Value[vals.size()]));
} else if (val instanceof short[]) {
ArrayList<Value> vals = new ArrayList<Value>();
short[] arr$ = (short[])val;
int len$ = arr$.length;
for (int i$ = 0; i$ < len$; ++i$) {
Short i = arr$[i$];
vals.add(node.getSession().getValueFactory().createValue((long)i.shortValue()));
}
p = node.setProperty(name, vals.toArray((T[])new Value[vals.size()]));
} else if (val instanceof String) {
p = node.setProperty(name, (String)val);
} else {
log.warn("Cannot handle as the type is not supported for the xmp property(" + prop.getPath() + ")");
}
}
catch (Throwable re) {
if (log.isDebugEnabled()) {
log.debug("Cannot set xmp property (" + prop.getPath() + "): " + re.getMessage(), re);
}
log.warn("Cannot set xmp property (" + prop.getPath() + "): " + re.getMessage());
}
return p;
}
private Object checkExif(String name, Object val) {
if (name.startsWith("exif:") && val instanceof byte[]) {
return new String((byte[])val);
}
return val;
}
private Property setMvProperty(Node node, List<XMPPropertyInfo> props, String name) {
Property p = null;
ArrayList<Value> vals = new ArrayList<Value>();
try {
Object val = this.checkForDate(props.get(0).getOriValue());
if (node.hasProperty(name) && !"xmpMM:Ingredients".equalsIgnoreCase(name)) {
Property existingProp = node.getProperty(name);
if (existingProp.isMultiple()) {
vals.addAll(Arrays.asList(existingProp.getValues()));
} else {
vals.add(existingProp.getValue());
existingProp.remove();
}
}
if (val instanceof Boolean) {
for (XMPPropertyInfo prop : props) {
if (this.hasDuplicate(vals, prop.getOriValue())) continue;
vals.add(node.getSession().getValueFactory().createValue(((Boolean)prop.getOriValue()).booleanValue()));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
} else if (val instanceof Long) {
for (XMPPropertyInfo prop : props) {
if (this.hasDuplicate(vals, prop.getOriValue())) continue;
vals.add(node.getSession().getValueFactory().createValue(((Long)prop.getOriValue()).longValue()));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
} else if (val instanceof Double) {
for (XMPPropertyInfo prop : props) {
Double value = (Double)prop.getOriValue();
double d = value.isInfinite() || value.isNaN() ? 0.0 : value;
value = d;
if (this.hasDuplicate(vals, value)) continue;
vals.add(node.getSession().getValueFactory().createValue(value.doubleValue()));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
} else if (val instanceof XMPDateTime) {
for (XMPPropertyInfo prop : props) {
Calendar cal = ((XMPDateTime)prop.getOriValue()).getCalendar();
if (this.hasDuplicate(vals, cal)) continue;
vals.add(node.getSession().getValueFactory().createValue(cal));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
} else if (val instanceof byte[]) {
for (XMPPropertyInfo prop : props) {
Binary binary = node.getSession().getValueFactory().createBinary((InputStream)new ByteArrayInputStream((byte[])prop.getOriValue()));
vals.add(node.getSession().getValueFactory().createValue(binary));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
} else if (val instanceof Date) {
for (XMPPropertyInfo prop : props) {
Calendar cal = Calendar.getInstance();
cal.setTime((Date)this.checkForDate(prop.getOriValue()));
if (this.hasDuplicate(vals, cal)) continue;
vals.add(node.getSession().getValueFactory().createValue(cal));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
} else {
for (XMPPropertyInfo prop : props) {
if (this.hasDuplicate(vals, prop.getOriValue())) continue;
vals.add(node.getSession().getValueFactory().createValue((String)prop.getOriValue()));
}
p = node.setProperty(name, vals.toArray((T[])new Value[props.size()]));
}
}
catch (Throwable re) {
log.warn("Cannot set xmp mv property (" + name + "): " + re.getMessage());
}
return p;
}
private boolean hasDuplicate(List<Value> values, Object value) {
if (value instanceof Boolean) {
for (Value val : values) {
try {
if (val.getBoolean() != ((Boolean)value).booleanValue()) continue;
return true;
}
catch (RepositoryException re) {
continue;
}
}
} else if (value instanceof Long) {
for (Value val : values) {
try {
if (val.getLong() != ((Long)value).longValue()) continue;
return true;
}
catch (RepositoryException re) {
continue;
}
}
} else if (value instanceof Calendar) {
for (Value val : values) {
try {
if (!val.getDate().equals(value)) continue;
return true;
}
catch (RepositoryException re) {
continue;
}
}
} else if (value instanceof Double) {
for (Value val : values) {
try {
if (val.getDouble() != ((Double)value).doubleValue()) continue;
return true;
}
catch (RepositoryException re) {
continue;
}
}
} else {
for (Value val : values) {
try {
if (!val.getString().equals((String)value)) continue;
return true;
}
catch (RepositoryException re) {
continue;
}
}
}
return false;
}
private Object checkForDate(Object val) {
if (val instanceof String) {
Date date = DateParser.parseDate((String)val);
return date == null ? val : date;
}
return val;
}
private Object getValue(Property prop) {
byte[] val;
block10 : {
val = null;
try {
switch (prop.getType()) {
case 2: {
val = IOUtils.toByteArray((InputStream)prop.getBinary().getStream());
break block10;
}
case 5: {
val = XMPDateTimeFactory.createFromCalendar((Calendar)prop.getDate());
break block10;
}
case 6: {
val = prop.getBoolean();
break block10;
}
case 4: {
val = prop.getDouble();
break block10;
}
case 3: {
val = prop.getLong();
break block10;
}
}
val = prop.getString();
}
catch (RepositoryException re) {
log.warn("Problem while getting xmp value from jcr property: " + re.getMessage());
}
catch (IOException ioe) {
log.warn("Problem while getting binary xmp value from jcr property: " + ioe.getMessage());
}
}
return val;
}
private Object[] getMultiValues(Property prop) {
ArrayList<Object> valueList;
valueList = new ArrayList<Object>();
try {
Value[] values = prop.getValues();
switch (prop.getType()) {
case 2: {
for (Value v : values) {
valueList.add(IOUtils.toByteArray((InputStream)v.getBinary().getStream()));
}
break;
}
case 5: {
for (Value v : values) {
valueList.add((Object)XMPDateTimeFactory.createFromCalendar((Calendar)v.getDate()));
}
break;
}
case 6: {
for (Value v : values) {
valueList.add(v.getBoolean());
}
break;
}
case 4: {
for (Value v : values) {
valueList.add(v.getDouble());
}
break;
}
case 3: {
for (Value v : values) {
valueList.add(v.getLong());
}
break;
}
default: {
for (Value v : values) {
valueList.add(v.getString());
}
}
}
}
catch (RepositoryException re) {
log.warn("Problem while getting xmp value from jcr property: " + re.getMessage());
}
catch (IOException ioe) {
log.warn("Problem while getting binary xmp value from jcr property: " + ioe.getMessage());
}
return valueList.toArray(new Object[valueList.size()]);
}
private void checkNamespace(XMPPropertyInfo prop, Node metadataRoot) throws RepositoryException {
this.checkNamespace(prop.getNamespace(), metadataRoot);
}
private String checkNamespace(String namespace, Node metadataRoot) throws RepositoryException {
try {
return metadataRoot.getSession().getWorkspace().getNamespaceRegistry().getPrefix(namespace);
}
catch (NamespaceException e) {
String prefix = XMPMetaFactory.getSchemaRegistry().getNamespacePrefix(namespace);
prefix = prefix.indexOf(":") > 0 ? prefix.substring(0, prefix.indexOf(":")) : prefix;
try {
metadataRoot.getSession().getWorkspace().getNamespaceRegistry().registerNamespace(prefix, namespace);
return metadataRoot.getSession().getWorkspace().getNamespaceRegistry().getPrefix(namespace);
}
catch (RepositoryException re) {
log.warn("Unable to register the namespace:" + namespace);
return prefix;
}
}
}
private String registerNs(String nsPrefix, String namespace) throws XMPException {
String regPrefix = XMPMetaFactory.getSchemaRegistry().getNamespacePrefix(namespace) == null ? XMPMetaFactory.getSchemaRegistry().registerNamespace(namespace, nsPrefix) : XMPMetaFactory.getSchemaRegistry().getNamespacePrefix(namespace);
return regPrefix.indexOf(":") > 0 ? regPrefix.substring(0, regPrefix.indexOf(":")) : regPrefix;
}
static {
altArrayProps = new ArrayList<String>(8);
altArrayProps.add("dc:description");
altArrayProps.add("dc:title");
altArrayProps.add("dc:rights");
altArrayProps.add("xmpRights:UsageTerms");
altArrayProps.add("exif:UserComment");
altArrayProps.add("tiff:Copyright");
altArrayProps.add("tiff:ImageDescription");
ignoreHierarchy = new ArrayList<String>();
ignoreHierarchy.add("dc:description");
ignoreHierarchy.add("dc:title");
ignoreHierarchy.add("dc:rights");
ignoreHierarchy.add("xmpRights:UsageTerms");
ignoreHierarchy.add("exif:UserComment");
ignoreHierarchy.add("tiff:Copyright");
ignoreHierarchy.add("tiff:ImageDescription");
ignoreHierarchy.add("cq:tags");
ignoreHierarchy.add("dc:creator");
ignoreHierarchy.add("creator");
ignoreHierarchy.add("dc:contributor");
ignoreHierarchy.add("dc:language");
ignoreHierarchy.add("dc:subject");
ignoreHierarchy.add("photoshop:SupplementalCategories");
}
}