DamUtil.java
33.3 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.internal.pdftoolkit.core.util.Utility
* com.day.cq.dam.api.Asset
* com.day.cq.dam.api.Rendition
* com.day.cq.dam.api.thumbnail.ThumbnailConfig
* javax.jcr.ItemNotFoundException
* javax.jcr.Node
* javax.jcr.PathNotFoundException
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Value
* javax.jcr.ValueFactory
* javax.jcr.Workspace
* javax.jcr.nodetype.NodeType
* javax.jcr.query.QueryManager
* javax.jcr.query.QueryResult
* javax.jcr.query.Row
* javax.jcr.query.RowIterator
* javax.jcr.query.qom.And
* javax.jcr.query.qom.Column
* javax.jcr.query.qom.Comparison
* javax.jcr.query.qom.Constraint
* javax.jcr.query.qom.DynamicOperand
* javax.jcr.query.qom.Join
* javax.jcr.query.qom.JoinCondition
* javax.jcr.query.qom.Literal
* javax.jcr.query.qom.Ordering
* javax.jcr.query.qom.PropertyValue
* javax.jcr.query.qom.QueryObjectModel
* javax.jcr.query.qom.QueryObjectModelFactory
* javax.jcr.query.qom.SameNodeJoinCondition
* javax.jcr.query.qom.Selector
* javax.jcr.query.qom.Source
* javax.jcr.query.qom.StaticOperand
* org.apache.commons.imaging.ImageReadException
* org.apache.commons.imaging.Imaging
* org.apache.commons.lang.StringUtils
* org.apache.jackrabbit.api.security.user.User
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ResourceUtil
* org.apache.sling.api.resource.ValueMap
* org.apache.sling.resource.collection.ResourceCollection
* org.apache.sling.tenant.Tenant
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.dam.commons.util;
import com.adobe.internal.pdftoolkit.core.util.Utility;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.api.thumbnail.ThumbnailConfig;
import com.day.cq.dam.commons.util.DateParser;
import com.day.cq.dam.commons.util.PrefixRenditionPicker;
import com.day.cq.dam.commons.util.UIHelper;
import java.awt.Dimension;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeType;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.jcr.query.Row;
import javax.jcr.query.RowIterator;
import javax.jcr.query.qom.And;
import javax.jcr.query.qom.Column;
import javax.jcr.query.qom.Comparison;
import javax.jcr.query.qom.Constraint;
import javax.jcr.query.qom.DynamicOperand;
import javax.jcr.query.qom.Join;
import javax.jcr.query.qom.JoinCondition;
import javax.jcr.query.qom.Literal;
import javax.jcr.query.qom.Ordering;
import javax.jcr.query.qom.PropertyValue;
import javax.jcr.query.qom.QueryObjectModel;
import javax.jcr.query.qom.QueryObjectModelFactory;
import javax.jcr.query.qom.SameNodeJoinCondition;
import javax.jcr.query.qom.Selector;
import javax.jcr.query.qom.Source;
import javax.jcr.query.qom.StaticOperand;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.resource.collection.ResourceCollection;
import org.apache.sling.tenant.Tenant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DamUtil {
private static final Logger log = LoggerFactory.getLogger(DamUtil.class);
private static final String[] IMG_MIME_TYPES = new String[]{"image/png", "image/jpeg", "image/tiff", "image/png", "image/bmp", "image/gif", "image/pjpeg", "image/x-portable-anymap", "image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap", "image/x-rgb", "image/x-xbitmap", "image/x-xpixmap", "image/x-icon", "image/photoshop", "image/x-photoshop", "image/psd", "application/photoshop", "application/psd", "image/vnd.adobe.photoshop"};
private static final String[] VID_MIME_TYPES = new String[]{"video/m4v", "video/flv", "video/avi", "video/mov", "video/3gpp", "application/x-troff-msvideo", "video/vnd", "model/vnd.mts", "video/ts", "video/vnd", "video/dvd", "video/x-ms-wmv", "video/msvideo", "video/x-msvideo", "video/x-flv", "video/mpeg", "video/x-mpeg", "video/x-m4v", "video/mpg", "video/x-mpg", "video/mpeg2", "video/x-mpeg2a", "video/mts", "video/x-ms-asf", "video/3gpp2", "video/x-f4v", "video/f4v", "video/m2p", "video/mp2t", "video/avchd-stream", "video/m2ts", "video/mp2t", "video/vnd.dlna.mpeg-tts", "video/m2v", "video/quicktime", "video/x-quicktime", "video/mp4", "video/ogg", "video/x-mxf", "application/mxf", "video/x-matroska", "video/mj2", "video/vnd.rn-realvideo", "application/vnd.rn-realmedia", "video/webm"};
private static final List<String> IMG_MIME_TYPE = Arrays.asList(IMG_MIME_TYPES);
private static final List<String> VID_MIME_TYPE = Arrays.asList(VID_MIME_TYPES);
private static final int MAGIC_SIZE = 1024;
public static String assetToBinaryPath(String path) {
String binaryPath = null;
if (StringUtils.startsWith((String)path, (String)"/content/dam")) {
binaryPath = StringUtils.replaceOnce((String)path, (String)"/content/dam", (String)"/var/dam");
}
return binaryPath;
}
public static String binaryToAssetPath(String path) {
String assetPath = null;
if (StringUtils.startsWith((String)path, (String)"/var/dam")) {
assetPath = StringUtils.replaceOnce((String)path, (String)"/var/dam", (String)"/content/dam");
}
return assetPath;
}
public static boolean isThumbnail(Node file) {
try {
return file.isNodeType("nt:file") && file.getName().startsWith("cq5dam.thumbnail");
}
catch (RepositoryException re) {
return false;
}
}
public static String getThumbnailName(int width, int height) {
return DamUtil.getThumbnailName(width, height, null);
}
public static String getThumbnailName(ThumbnailConfig config) {
String[] arrstring;
if (config.doCenter()) {
String[] arrstring2 = new String[1];
arrstring = arrstring2;
arrstring2[0] = "margin";
} else {
arrstring = null;
}
String[] selectors = arrstring;
return DamUtil.getThumbnailName(config.getWidth(), config.getHeight(), selectors);
}
public static String getThumbnailName(int width, int height, String[] selectors) {
String selectorString = StringUtils.join((Object[])(selectors = null != selectors ? selectors : new String[]{}), (char)'.');
if (!"".equals(selectorString)) {
selectorString = "." + selectorString;
}
return "cq5dam.thumbnail." + String.valueOf(width) + "." + String.valueOf(height) + selectorString + ".png";
}
public static boolean isRendition(Resource resource) {
if (null == resource) {
return false;
}
Resource parent = ResourceUtil.getParent((Resource)resource);
if (null == parent) {
return false;
}
Resource content = ResourceUtil.getParent((Resource)parent);
if (null == content) {
return false;
}
Resource asset = ResourceUtil.getParent((Resource)content);
if (null == asset) {
return false;
}
return "renditions".equals(ResourceUtil.getName((Resource)parent)) && (DamUtil.isAsset(asset) || DamUtil.isFrozenNode(asset));
}
public static boolean isMetadataRes(Resource resource) {
if (null == resource || !"metadata".equals(ResourceUtil.getName((Resource)resource))) {
return false;
}
Resource content = ResourceUtil.getParent((Resource)resource);
if (null == content) {
return false;
}
Resource asset = ResourceUtil.getParent((Resource)content);
if (null == asset) {
return false;
}
return DamUtil.isAsset(asset) || DamUtil.isFrozenNode(asset);
}
public static Asset getAssetFromMetaRes(Resource resource) {
if (null == resource || !"metadata".equals(ResourceUtil.getName((Resource)resource))) {
return null;
}
Resource content = ResourceUtil.getParent((Resource)resource);
if (null == content) {
return null;
}
Resource asset = ResourceUtil.getParent((Resource)content);
if (null == asset) {
return null;
}
if (DamUtil.isAsset(asset) || DamUtil.isFrozenNode(asset)) {
return (Asset)asset.adaptTo(Asset.class);
}
return null;
}
public static boolean isAsset(Resource resource) {
return null != resource && "dam:Asset".equals(resource.getResourceType());
}
public static boolean isFrozenNode(Resource resource) {
return null != resource && "nt:frozenNode".equals(resource.getResourceType());
}
public static boolean isSubAsset(Resource resource) {
return DamUtil.isAsset(resource) && "subassets".equals(ResourceUtil.getName((Resource)ResourceUtil.getParent((Resource)resource)));
}
public static Asset resolveToAsset(Resource resource) {
if (null != resource && DamUtil.isAsset(resource)) {
return (Asset)resource.adaptTo(Asset.class);
}
Resource parent = ResourceUtil.getParent((Resource)resource);
if (null != parent) {
return DamUtil.resolveToAsset(parent);
}
return null;
}
public static void setModified(Asset asset, String user, Calendar date) {
try {
Node contentNode = ((Node)asset.adaptTo(Node.class)).getNode("jcr:content");
contentNode.setProperty("jcr:lastModifiedBy", user);
contentNode.setProperty("jcr:lastModified", date);
contentNode.getSession().save();
}
catch (RepositoryException e) {
// empty catch block
}
}
public static List<String> findExpiringAssets(Session session, Calendar lowerBound, Calendar upperBound) throws RepositoryException {
ArrayList<String> results = null;
QueryObjectModel qom = null;
try {
QueryManager queryManager = session.getWorkspace().getQueryManager();
QueryObjectModelFactory qomf = queryManager.getQOMFactory();
Selector damAsset = qomf.selector("dam:Asset", "selector_0");
Selector assetContent = qomf.selector("dam:AssetContent", "selector_1");
ValueFactory vf = session.getValueFactory();
PropertyValue expiryDateOprnd = qomf.propertyValue("selector_1", "offTime");
Comparison expiryDateConstrnt = null;
Comparison upperBndConstrnt = null;
if (upperBound != null) {
Literal upperBndOprnd = qomf.literal(vf.createValue(upperBound));
expiryDateConstrnt = upperBndConstrnt = qomf.comparison((DynamicOperand)expiryDateOprnd, "jcr.operator.less.than", (StaticOperand)upperBndOprnd);
}
if (lowerBound != null) {
Literal lowerBndOprnd = qomf.literal(vf.createValue(lowerBound));
Comparison lowerBndConstrnt = qomf.comparison((DynamicOperand)expiryDateOprnd, "jcr.operator.greater.than.or.equal.to", (StaticOperand)lowerBndOprnd);
expiryDateConstrnt = upperBndConstrnt != null ? qomf.and((Constraint)upperBndConstrnt, (Constraint)lowerBndConstrnt) : lowerBndConstrnt;
}
SameNodeJoinCondition joinAssetToJcrContent = qomf.sameNodeJoinCondition("selector_1", "selector_0", "jcr:content");
assetContent = qomf.join((Source)damAsset, (Source)assetContent, "jcr.join.type.inner", (JoinCondition)joinAssetToJcrContent);
qom = qomf.createQuery((Source)assetContent, (Constraint)expiryDateConstrnt, null, null);
if (log.isDebugEnabled()) {
log.debug("Expiring assets query [{}].", (Object)qom.getStatement());
}
long startTime = 0;
if (log.isTraceEnabled()) {
startTime = System.currentTimeMillis();
}
QueryResult result = qom.execute();
if (log.isTraceEnabled()) {
long endTime = System.currentTimeMillis();
log.trace("Time taken to execute query [{}] ms", (Object)new Long(endTime - startTime));
}
RowIterator rowIter = result.getRows();
long resultSize = rowIter.getSize();
results = new ArrayList<String>(new Long(resultSize).intValue());
if (log.isDebugEnabled()) {
log.debug("ResultSet size [{}].", (Object)resultSize);
}
if (log.isTraceEnabled()) {
log.trace("Logging search result set");
}
while (rowIter.hasNext()) {
Row row = rowIter.nextRow();
Node node = row.getNode("selector_0");
String path = node.getPath();
if (log.isTraceEnabled()) {
log.trace("path [{}]", (Object)path);
}
results.add(path);
}
}
catch (RepositoryException e) {
if (qom != null) {
log.error("Expired assets query [{}].", (Object)qom.getStatement());
}
log.error("Error in finding expired assets", (Throwable)e);
throw e;
}
return results;
}
public static boolean isExpiredAsset(Asset asset) {
boolean isAssetExpired = false;
if (null != asset) {
Calendar now = Calendar.getInstance();
Calendar assetExpiryTime = DamUtil.getExpiryTime(asset);
if (null != assetExpiryTime) {
isAssetExpired = assetExpiryTime.before(now);
}
}
return isAssetExpired;
}
public static boolean isExpiredAsset(Resource resource) {
return DamUtil.isExpiredAsset((Asset)resource.adaptTo(Asset.class));
}
public static boolean isExpiredSubAsset(Resource resource) {
boolean isAssetExpired = false;
boolean isSubAssetExpired = false;
Asset asset = (Asset)resource.adaptTo(Asset.class);
if (null != asset && !(isAssetExpired = DamUtil.isExpiredAsset(asset))) {
Calendar now = Calendar.getInstance();
Collection subAssets = asset.getSubAssets();
List<Asset> refSubAssets = DamUtil.getReferencedSubAssets(resource);
if (null != refSubAssets) {
subAssets.addAll(refSubAssets);
}
ResourceResolver resolver = resource.getResourceResolver();
for (Asset each : subAssets) {
Calendar subAssetExpiryTime;
Resource subRes = resolver.getResource(each.getPath());
Node subNode = (Node)subRes.adaptTo(Node.class);
if (null == subNode || null == (subAssetExpiryTime = DamUtil.getExpiryTime(each)) || !subAssetExpiryTime.before(now)) continue;
isSubAssetExpired = subAssetExpiryTime.before(now);
break;
}
}
return isSubAssetExpired;
}
public static String getValue(Node n, String name, String defaultValue) throws RepositoryException {
if (n == null) {
return defaultValue;
}
try {
Property p = n.getProperty(name);
if (!p.isMultiple()) {
return p.getString();
}
Value[] values = p.getValues();
String val = "";
boolean first = true;
for (Value a : values) {
if (!first) {
val = val + ", ";
} else {
first = false;
}
val = val + a.getString();
}
return val;
}
catch (PathNotFoundException e) {
return defaultValue;
}
}
public static boolean isImage(Asset asset) {
return IMG_MIME_TYPE.contains(asset.getMimeType());
}
public static boolean isVideo(Asset asset) {
String[] errantTypes = new String[]{"mpv", "m2ts", "m2t", "m2p", "vob", "ts", "webm", "mkv"};
List<String> errantList = Arrays.asList(errantTypes);
return VID_MIME_TYPE.contains(asset.getMimeType()) || asset.getMimeType() == null && errantList.contains(StringUtils.substringAfterLast((String)asset.getName(), (String)".").toLowerCase());
}
public static boolean isSmartCollection(Resource resource) {
return resource.isResourceType("dam/smartcollection");
}
public static Node getApplicableProfile(Asset asset, String profileType, Session session) {
try {
Node assetNode = (Node)asset.adaptTo(Node.class);
String path = "";
if (null != assetNode) {
Node parentNode = assetNode.getParent();
while (!parentNode.getPath().equals("/content")) {
if (!parentNode.getPrimaryNodeType().getName().equals("dam:Asset") && parentNode.hasProperty("jcr:content/" + profileType) && session.nodeExists(path = parentNode.getProperty("jcr:content/" + profileType).getString())) {
return session.getNode(path);
}
parentNode = parentNode.getParent();
}
}
}
catch (RepositoryException e) {
log.error("Unable to retrieve applicable profile", (Throwable)e);
}
return null;
}
@Deprecated
public static String getAppliedProcessingProfilePath(Asset asset) {
return null;
}
public static Iterator<Asset> getAssets(Resource res) {
Asset asset = (Asset)res.adaptTo(Asset.class);
if (asset == null) {
return new FolderAssetIterator(res);
}
return Collections.singletonList(asset).iterator();
}
public static boolean checkforAIFile(Asset asset) {
if (asset != null && asset.getOriginal() != null) {
InputStream in = asset.getOriginal().getStream();
PushbackInputStream pin = new PushbackInputStream(in, 1024);
byte[] data = new byte[1024];
try {
int len = pin.read(data);
if (len <= 0) {
return false;
}
pin.unread(data, 0, len);
byte[] pdfMarker = new byte[]{37, 80, 68, 70, 45};
int size = 1024;
if (size > len) {
size = len;
}
byte[] header = new byte[size];
System.arraycopy(data, 0, header, 0, size);
long result = Utility.KMPFindFirst((byte[])pdfMarker, (int[])Utility.ComputeKMPNextArray((byte[])pdfMarker), (byte[])header);
return result >= 0;
}
catch (IOException e) {
log.warn("I/O error while getting metadata.", (Throwable)e);
}
}
return false;
}
public static Rendition getBestFitRendition(int width, List<Rendition> renditions) {
Rendition rend;
PrefixRenditionPicker prefixPicker = new PrefixRenditionPicker("cq5dam.thumbnail." + width);
Rendition bestFitRendition = prefixPicker.getRendition(renditions.iterator());
if (bestFitRendition == null) {
prefixPicker = new PrefixRenditionPicker("cq5dam.web." + width);
bestFitRendition = prefixPicker.getRendition(renditions.iterator());
}
if (bestFitRendition != null) {
return bestFitRendition;
}
WidthBasedRenditionComparator comp = new WidthBasedRenditionComparator();
Collections.sort(renditions, comp);
Iterator<Rendition> itr = renditions.iterator();
Rendition bestFit = null;
while (itr.hasNext()) {
int w;
rend = itr.next();
if (!UIHelper.canRenderOnWeb(rend.getMimeType()) || (w = UIHelper.getWidth(rend)) > width) continue;
bestFit = rend;
}
itr = renditions.iterator();
if (bestFit == null) {
while (itr.hasNext()) {
rend = itr.next();
if (!UIHelper.canRenderOnWeb(rend.getMimeType())) continue;
bestFit = rend;
break;
}
}
return bestFit;
}
public static Dimension getImageDimension(InputStream is, String filename) {
Dimension imageDimension = new Dimension(0, 0);
try {
imageDimension = Imaging.getImageSize((InputStream)is, (String)filename);
}
catch (ImageReadException ex) {
log.error("Error in getting image dimension for rendition : " + filename, (Throwable)ex);
return imageDimension;
}
catch (IOException ex) {
log.error("Error in getting image dimension for rendition : " + filename, (Throwable)ex);
return imageDimension;
}
return imageDimension;
}
public static boolean expiryStatus(Asset asset) {
return false;
}
public static List<Asset> getReferencedSubAssets(Resource resource) {
ArrayList<Asset> refAssets = new ArrayList<Asset>();
try {
Node node = (Node)resource.adaptTo(Node.class);
if (node == null || !node.hasProperty("jcr:content/related/links/sling:members/sling:resources")) {
return refAssets;
}
Property prop = ((Node)resource.adaptTo(Node.class)).getProperty("jcr:content/related/links/sling:members/sling:resources");
if (null != prop) {
Value[] values;
for (Value each : values = prop.getValues()) {
Asset refAsset;
Resource resEach = resource.getResourceResolver().getResource(each.getString());
if (null == resEach || null == (refAsset = (Asset)resEach.adaptTo(Asset.class))) continue;
refAssets.add(refAsset);
}
}
}
catch (RepositoryException e) {
log.error("Error in getting referenced sub assets", (Throwable)e);
return refAssets;
}
return refAssets;
}
public static Collection<Asset> getSubAssets(Resource resource) {
Asset asset;
Collection assets = new LinkedList<Asset>();
if (null != resource && null != (asset = (Asset)resource.adaptTo(Asset.class))) {
assets = asset.getSubAssets();
}
return assets;
}
public static Collection<Asset> getRefererAssets(ResourceResolver resolver, String path) {
String root = "/jcr:root/content/dam";
String sub = "[jcr:content/related/links/sling:members/*/@dam:resolvedPath='%s']";
String query = String.format("%s//*" + sub, root, path);
log.debug("Find Referer Query:{0}", (Object)query);
Iterator iter = resolver.findResources(query, "xpath");
ArrayList<Asset> assets = new ArrayList<Asset>();
while (iter.hasNext()) {
Resource res = (Resource)iter.next();
Asset asset = null;
if (null != res) {
asset = (Asset)res.adaptTo(Asset.class);
}
if (null != asset) {
assets.add(asset);
continue;
}
Node node = (Node)res.adaptTo(Node.class);
try {
Resource res1;
String assetPath;
if (!node.hasProperty("dam:resolvedPath") || null == (res1 = resolver.getResource(assetPath = node.getProperty("dam:resolvedPath").getString())) || null == (asset = (Asset)res1.adaptTo(Asset.class))) continue;
assets.add(asset);
}
catch (RepositoryException e) {
log.error("", (Throwable)e);
}
}
return assets;
}
public static Calendar getExpiryTime(Asset asset) {
Date date;
if (asset == null) {
return null;
}
String value = asset.getMetadataValueFromJcr("prism:expirationDate");
if (StringUtils.isNotEmpty((String)value) && (date = DateParser.parseDate(value)) != null) {
Calendar result = Calendar.getInstance();
result.setTime(date);
return result;
}
return null;
}
public static Asset getParentAsset(Resource resource) {
if (null != resource && DamUtil.isSubAsset(resource)) {
return (Asset)resource.getParent().getParent().adaptTo(Asset.class);
}
if (null == resource) {
log.error("Resource NULL.");
} else {
log.error("Resource {0} is not a sub-asset", (Object)resource.getPath());
}
return null;
}
public static boolean isValid(Asset asset) throws RepositoryException {
return DamUtil.isValid((Node)asset.adaptTo(Node.class));
}
public static String getTenantAssetsRoot(ResourceResolver resolver) {
Tenant tenant;
User user = (User)resolver.adaptTo(User.class);
String mountPoint = "/content/dam";
if (user != null && !user.isSystemUser() && (tenant = (Tenant)resolver.adaptTo(Tenant.class)) != null) {
mountPoint = (String)tenant.getProperty("dam:assetsRoot");
}
return mountPoint;
}
public static String getTenantAssetsRoot(ResourceResolver resolver, String assetPath) {
Resource assetResource = resolver.getResource(assetPath);
if (assetResource == null) {
return "/content/dam";
}
Tenant tenant = (Tenant)assetResource.adaptTo(Tenant.class);
if (tenant == null) {
return "/content/dam";
}
return (String)tenant.getProperty("dam:assetsRoot");
}
public static String getTenantAssetsRoot(Resource resource) {
if (resource == null) {
return "/content/dam";
}
Tenant tenant = (Tenant)resource.adaptTo(Tenant.class);
if (tenant == null) {
return "/content/dam";
}
return (String)tenant.getProperty("dam:assetsRoot");
}
public static Asset getAssetFromID(ResourceResolver resolver, String id) throws RepositoryException {
try {
Node assetNode = ((Session)resolver.adaptTo(Session.class)).getNodeByIdentifier(id);
return (Asset)resolver.getResource(assetNode.getPath()).adaptTo(Asset.class);
}
catch (ItemNotFoundException ign) {
return null;
}
catch (IllegalArgumentException ign) {
return null;
}
}
public static String findRelativePathOfAssetNode(Node assetNode, String assetsRoot) throws RepositoryException {
String assetAbsPath = assetNode.getPath();
int idx = -1;
idx = assetAbsPath.indexOf(assetsRoot);
if (0 <= idx) {
idx += assetsRoot.length();
}
return assetAbsPath.substring(idx + 1);
}
private static boolean isValid(Node assetNode) throws RepositoryException {
return DamUtil.timeUntilValid(assetNode) == 0;
}
private static long timeUntilValid(Node assetNode) throws RepositoryException {
long timeUntilOff;
long timeUntilOn;
if (!DamUtil.hasContent(assetNode)) {
return Long.MIN_VALUE;
}
Calendar onTime = DamUtil.getOnTime(assetNode);
Calendar offTime = DamUtil.getOffTime(assetNode);
if (onTime == null && offTime == null) {
return 0;
}
long now = System.currentTimeMillis();
long l = timeUntilOn = onTime == null ? 0 : onTime.getTimeInMillis() - now;
if (timeUntilOn > 0) {
return timeUntilOn;
}
long l2 = timeUntilOff = offTime == null ? 0 : offTime.getTimeInMillis() - now;
if (timeUntilOff < 0) {
return timeUntilOff;
}
return 0;
}
private static boolean hasContent(Node assetNode) throws RepositoryException {
return assetNode.hasNode("jcr:content");
}
private static Calendar getOnTime(Node assetNode) throws RepositoryException {
if (DamUtil.hasContent(assetNode) && assetNode.getNode("jcr:content").hasProperty("onTime")) {
return assetNode.getNode("jcr:content").getProperty("onTime").getDate();
}
return null;
}
private static Calendar getOffTime(Node assetNode) throws RepositoryException {
if (DamUtil.hasContent(assetNode) && assetNode.getNode("jcr:content").hasProperty("offTime")) {
return assetNode.getNode("jcr:content").getProperty("offTime").getDate();
}
return null;
}
private static <T> T getInheritedProperty(String property, Resource resource, Class<T> type) {
if (null == type) {
log.debug("type argument can't be null");
return null;
}
if (StringUtils.isBlank((String)property)) {
log.debug("property name can't be empty");
return null;
}
if (null == resource) {
log.debug("content resource could not be null");
return null;
}
Object value = null;
while (null != resource) {
ValueMap propertiesMap = (ValueMap)resource.adaptTo(ValueMap.class);
if (null != propertiesMap && propertiesMap.containsKey((Object)property)) {
value = propertiesMap.get(property, type);
break;
}
resource = resource.getParent();
}
if (null == value) {
if (null == resource) {
log.debug("property {} not found on the content path", (Object)property);
} else {
log.debug("property value retrived could not be converted to {}", (Object)type.getName());
}
return null;
}
return (T)value;
}
public static <T> T getInheritedProperty(String property, Resource resource, T defaultValue) {
if (null == defaultValue) {
log.debug("defaultValue argument cant be null");
return null;
}
Class value = DamUtil.getInheritedProperty(property, resource, defaultValue.getClass());
if (null != value) {
return (T)value;
}
return defaultValue;
}
private static class FolderAssetIterator
implements Iterator<Asset> {
private Resource parentResource;
private Iterator<Resource> it = null;
private List<Resource> parentNodes = new ArrayList<Resource>();
private Asset next = null;
private Iterator<Resource> getChildren(Resource res) {
ResourceCollection rc = (ResourceCollection)res.adaptTo(ResourceCollection.class);
if (rc != null) {
return rc.getResources();
}
return res.listChildren();
}
public FolderAssetIterator(Resource resource) {
this.parentResource = resource;
this.it = this.getChildren(this.parentResource);
this.next = this.getNext();
}
private Asset getNext() {
while (!this.it.hasNext() && !this.parentNodes.isEmpty()) {
this.it = this.getChildren(this.parentNodes.remove(0));
}
while (this.it.hasNext()) {
Resource member = this.it.next();
Node n = (Node)member.adaptTo(Node.class);
try {
if (n.isNodeType("dam:Asset")) {
return (Asset)member.adaptTo(Asset.class);
}
if (!n.isNodeType("nt:folder") && member.adaptTo(ResourceCollection.class) == null) continue;
this.parentNodes.add(member);
}
catch (RepositoryException e) {
log.error("unexpected exception ", (Throwable)e);
}
}
if (!this.parentNodes.isEmpty()) {
return this.getNext();
}
return null;
}
@Override
public boolean hasNext() {
return this.next != null;
}
@Override
public Asset next() {
Asset toReturn = this.next;
this.next = this.getNext();
return toReturn;
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove not allowed for asset iterator on folder listing");
}
}
private static class WidthBasedRenditionComparator
implements Comparator<Rendition> {
private WidthBasedRenditionComparator() {
}
@Override
public int compare(Rendition r1, Rendition r2) {
int w2;
int w1 = UIHelper.getWidth(r1);
if (w1 < (w2 = UIHelper.getWidth(r2))) {
return -1;
}
if (w1 == w2) {
return 0;
}
return 1;
}
}
}