AssetReferenceResolverImpl.java
24.5 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.cq.projects.api.Project
* com.adobe.granite.asset.api.Asset
* com.adobe.granite.asset.api.AssetRelation
* com.day.cq.dam.api.Asset
* com.day.cq.dam.api.AssetReferenceResolver
* javax.jcr.Item
* javax.jcr.Node
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* org.apache.commons.lang.StringUtils
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Service
* org.apache.jackrabbit.util.Text
* 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.tenant.Tenant
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.dam.core.impl;
import com.adobe.cq.projects.api.Project;
import com.adobe.granite.asset.api.AssetRelation;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetReferenceResolver;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.util.Text;
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.tenant.Tenant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component(inherit=1)
@Service
public class AssetReferenceResolverImpl
implements AssetReferenceResolver {
private static final Logger log = LoggerFactory.getLogger(AssetReferenceResolverImpl.class);
private static final String ORIGINAL_PATH = "dam:originalPath";
private static final String RESOLVED_PATH = "dam:resolvedPath";
private static final String REFERENCE_NODE = "links";
private static final String FILE_PATH_INITIAL = "file://";
private static final String RELATIONS_NODE = "related";
private static final String VOLUMES = "Volumes/";
private static final String XMP_MANIFEST_PATH = "jcr:content/metadata/xmpMM:Manifest";
private static final String FILE_REFERENCE_PATH = "stMfs:reference";
private static final String REF_FILE_PATH = "stRef:filePath";
private static final String REF_FILE_PATH_URL = "stRef:lastURL";
private static final String REF_INSTANCE_ID = "stRef:instanceID";
private static final String REF_INSTANCE_ID_PS = "stRef:InstanceID";
private static final String REF_DOCUMENT_ID = "stRef:documentID";
private static final String REF_DOCUMENT_ID_PS = "stRef:DocumentID";
private static final String XMP_INSTANCE_ID = "xmpMM:InstanceID";
private static final String XMP_DOCUMENT_ID = "xmpMM:DocumentID";
private static final String LINK_NODE = "links";
private static final String RELATIVE_REFERENCE_NODE = "jcr:content/related/links";
private static final String INGREDIENT_TAG = "xmpMM:Ingredients";
private static final String INGREDIENTS_PATH = "jcr:content/metadata/xmpMM:Ingredients";
private static final String LINKS_NODE = "links";
private static final String PROJECT_LINK_REF = "cq/gui/components/projects/admin/card/assetlinkcard";
public Iterator<? extends AssetRelation> resolve(Asset asset) {
com.adobe.granite.asset.api.Asset graniteAsset = (com.adobe.granite.asset.api.Asset)asset.adaptTo(com.adobe.granite.asset.api.Asset.class);
ResourceResolver resolver = graniteAsset.getResourceResolver();
if (asset == null || resolver == null) {
log.error("Error while resolving asset references");
return Collections.emptyList().iterator();
}
if (graniteAsset.getChild("jcr:content/related/links") != null) {
graniteAsset.removeRelation("links");
}
if (resolver.getResource(asset.getPath()).getChild("jcr:content/metadata/xmpMM:Ingredients") != null && !StringUtils.endsWithIgnoreCase((String)asset.getMimeType(), (String)"-indesign")) {
this.resolveThroughIngredient(asset, resolver);
} else {
this.resolveThroughManifest(asset, resolver);
}
return graniteAsset.listRelations("links");
}
private void resolveThroughIngredient(Asset asset, ResourceResolver resolver) {
Resource resource = resolver.getResource(asset.getPath());
try {
Resource ingredients = resource.getChild("jcr:content/metadata/xmpMM:Ingredients");
Iterator itr = ingredients.getChildren().iterator();
while (itr.hasNext()) {
String title = null;
String xmpinstanceID = null;
String xmpdocumentID = null;
Resource referenceNode = (Resource)itr.next();
if (referenceNode != null) {
ValueMap properties = (ValueMap)referenceNode.adaptTo(ValueMap.class);
title = (String)properties.get("stRef:filePath", String.class);
if (properties.containsKey((Object)"stRef:instanceID")) {
xmpinstanceID = (String)properties.get("stRef:instanceID", String.class);
} else if (properties.containsKey((Object)"stRef:InstanceID")) {
xmpinstanceID = (String)properties.get("stRef:InstanceID", String.class);
}
if (properties.containsKey((Object)"stRef:documentID")) {
xmpdocumentID = (String)properties.get("stRef:documentID", String.class);
} else if (properties.containsKey((Object)"stRef:DocumentID")) {
xmpdocumentID = (String)properties.get("stRef:DocumentID", String.class);
}
}
if (title == null) continue;
this.resolveAndAddReference(resolver, asset, title, xmpinstanceID, xmpdocumentID);
}
}
catch (Exception e) {
log.warn("Node Exception.", (Throwable)e);
}
}
private void resolveThroughManifest(Asset asset, ResourceResolver resolver) {
Resource resource = resolver.getResource(asset.getPath());
try {
Resource manifest = resource.getChild("jcr:content/metadata/xmpMM:Manifest");
if (manifest == null) {
log.warn("did not find - 'jcr:content/metadata/xmpMM:Manifest'");
return;
}
Iterator itr = manifest.getChildren().iterator();
while (itr.hasNext()) {
String title = null;
String xmpinstanceID = null;
String xmpdocumentID = null;
Resource referenceNode = ((Resource)itr.next()).getChild("stMfs:reference");
if (referenceNode != null) {
ValueMap properties = (ValueMap)referenceNode.adaptTo(ValueMap.class);
if (properties.containsKey((Object)"stRef:filePath")) {
title = (String)properties.get("stRef:filePath", String.class);
} else if (properties.containsKey((Object)"stRef:lastURL")) {
title = (String)properties.get("stRef:lastURL", String.class);
}
xmpinstanceID = (String)properties.get("stRef:instanceID", String.class);
xmpdocumentID = (String)properties.get("stRef:documentID", String.class);
}
if (title == null) continue;
this.resolveAndAddReference(resolver, asset, title, xmpinstanceID, xmpdocumentID);
}
}
catch (Exception e) {
log.warn("Node Exception.", (Throwable)e);
}
}
private boolean resolveAndAddReference(ResourceResolver resourceResolver, Asset asset, String originalPath, String xmpinstanceID, String xmpdocumentID) {
if (originalPath == null) {
return false;
}
Resource resource = resourceResolver.getResource(asset.getPath());
Tenant tenant = null;
if (null != resource) {
tenant = (Tenant)resource.adaptTo(Tenant.class);
}
originalPath = originalPath.replace("\\", "/");
originalPath = this.formatFileName(originalPath, asset);
boolean multipleReferences = false;
List resolvedPaths = new ArrayList<String>();
String resolvedPath = null;
String decodedPath = originalPath;
try {
decodedPath = URLDecoder.decode(originalPath, "UTF-8");
}
catch (UnsupportedEncodingException e) {
log.error("should not come, still let's log it", (Throwable)e);
}
if ((xmpinstanceID == null || xmpinstanceID.equals("0") || xmpinstanceID.trim().length() == 0) && (xmpdocumentID == null || xmpdocumentID.equals("0") || xmpdocumentID.trim().length() == 0)) {
resolvedPath = this.getResolvedPath(decodedPath, resourceResolver, tenant);
} else {
if (xmpinstanceID != null && !xmpinstanceID.equals("0") && xmpinstanceID.trim().length() != 0) {
resolvedPaths = this.getResolvedPathById(xmpinstanceID, "xmpMM:InstanceID", resourceResolver, tenant);
if (resolvedPaths.size() == 1) {
resolvedPath = (String)resolvedPaths.get(0);
} else if (resolvedPaths.size() > 1 && (resolvedPath = this.getResolvedPath(decodedPath, resourceResolver, tenant)) == null) {
multipleReferences = true;
}
}
if (xmpdocumentID != null && !xmpdocumentID.equals("0") && xmpdocumentID.trim().length() != 0 && (resolvedPaths.size() == 0 || xmpinstanceID == null || xmpinstanceID.equals("0") || xmpinstanceID.trim().length() == 0)) {
resolvedPaths = this.getResolvedPathById(xmpdocumentID, "xmpMM:DocumentID", resourceResolver, tenant);
String string = resolvedPath = resolvedPaths.size() == 1 ? (String)resolvedPaths.get(0) : this.getResolvedPath(decodedPath, resourceResolver, tenant);
if (resolvedPaths.size() > 1 && resolvedPath == null) {
multipleReferences = true;
}
}
}
if (resolvedPath != null || multipleReferences) {
if (resolvedPath != null) {
resolvedPaths.clear();
resolvedPaths.add((String)resolvedPath);
}
this.createReferences(resourceResolver, asset, originalPath, resolvedPaths);
return true;
}
String linksReferencePath1 = Text.getRelativeParent((String)asset.getPath(), (int)1) + "/" + "links" + "/" + Text.getName((String)originalPath);
String linksReferencePath2 = Text.getRelativeParent((String)asset.getPath(), (int)1) + "/" + "Links" + "/" + Text.getName((String)originalPath);
Session session = (Session)resourceResolver.adaptTo(Session.class);
try {
boolean links1 = session.itemExists(linksReferencePath1);
boolean links2 = session.itemExists(linksReferencePath2);
if (links1 || links2) {
resolvedPaths.clear();
if (links1) {
resolvedPaths.add(linksReferencePath1);
} else {
resolvedPaths.add(linksReferencePath2);
}
this.createReferences(resourceResolver, asset, originalPath, resolvedPaths);
return true;
}
}
catch (RepositoryException e) {
log.error("Unable to resolve the referenced link" + e.getMessage(), (Throwable)e);
}
return false;
}
private void createReferences(ResourceResolver resourceResolver, Asset asset, String originalPath, List<String> resolvedPaths) {
ArrayList<Object> data = new ArrayList<Object>();
data.add(originalPath);
for (String resolvedP : resolvedPaths) {
log.debug("Adding reference {} for {}", (Object)resolvedP, (Object)originalPath);
try {
this.createReference(asset.getPath(), false, resolvedP, data, resourceResolver);
}
catch (RepositoryException e) {
log.error("Error at reference node creation", (Object)e.getMessage());
}
}
}
private String formatFileName(String str, Asset asset) {
try {
str = Text.getRelativeParent((String)str, (int)1) + "/" + URLDecoder.decode(Text.getName((String)str), "UTF-8");
}
catch (UnsupportedEncodingException e) {
log.warn("formatFileName: Unable to decode the filename " + Text.getName((String)str) + " in the asset " + asset.getPath() + " Failed with exception: ", (Object)e.getMessage(), (Object)e);
}
return str;
}
/*
* Enabled force condition propagation
* Lifted jumps to return sites
*/
private String getResolvedPath(String originalPath, ResourceResolver resolver, Tenant tenant) {
Session session = (Session)resolver.adaptTo(Session.class);
String resolvedPath = null;
if (originalPath == null) {
return null;
}
String mountPoint = "/content/dam";
if (null != tenant) {
mountPoint = (String)tenant.getProperty("dam:assetsRoot");
}
if (originalPath.contains("file://")) {
originalPath = originalPath.substring(originalPath.indexOf("file://") + "file://".length());
}
String mp = mountPoint;
while (!mp.trim().isEmpty()) {
if (originalPath.contains(mp)) {
resolvedPath = mountPoint.substring(0, mountPoint.indexOf(mp)) + originalPath.substring(originalPath.indexOf(mp));
break;
}
mp = mp.substring(1);
int nextPathIndex = 0;
nextPathIndex = mp.indexOf("/");
if (nextPathIndex > -1) {
mp = mp.substring(nextPathIndex);
continue;
}
mp = "";
}
if (resolvedPath == null) {
String filePath;
if (!originalPath.contains("/")) return null;
if (originalPath.charAt(0) == '/') {
if (originalPath.length() <= 1) return null;
filePath = originalPath.substring(1);
} else {
filePath = originalPath;
}
if (!filePath.contains("/")) {
return null;
}
String driveName = filePath.substring(0, filePath.indexOf("/"));
int doubleSlashIndex = -1;
int colonIndex = driveName.indexOf(":");
if (colonIndex > 0) {
resolvedPath = mountPoint + filePath.substring(colonIndex + 1);
} else {
doubleSlashIndex = filePath.indexOf("//");
if (doubleSlashIndex > 0) {
resolvedPath = mountPoint + filePath.substring(doubleSlashIndex + 1);
} else {
if (!filePath.contains("/")) {
return null;
}
int volumeLabelIndex = filePath.indexOf("/");
if (filePath.startsWith("Volumes/")) {
volumeLabelIndex = filePath.indexOf("/", driveName.length() + 1);
}
String relativePath = filePath.substring(volumeLabelIndex);
resolvedPath = mountPoint + relativePath;
}
}
}
try {
if (!session.itemExists(resolvedPath)) return null;
return resolvedPath;
}
catch (RepositoryException e) {
log.error("Unable to resolve the referenced link" + e.getMessage(), (Throwable)e);
}
return null;
}
public String getResolvedPath(String originalPath, ResourceResolver resolver) {
return this.getResolvedPath(originalPath, resolver, null);
}
private List<String> getResolvedPathById(String id, String property, ResourceResolver resolver, Tenant tenant) {
if (id == null) {
return null;
}
ArrayList<String> linkedResources = new ArrayList<String>();
String query = null;
query = null != tenant ? "/jcr:root" + (String)tenant.getProperty("dam:assetsRoot") + "//element(*,dam:Asset)[(jcr:content/metadata/@" + property + " = '" + id + "')]" : "/jcr:root/content/dam//element(*,dam:Asset)[(jcr:content/metadata/@" + property + " = '" + id + "')]";
log.debug("Getting references for the asset {} by executing the query {} ", (Object)id, (Object)query);
Iterator rscItr = resolver.findResources(query, "xpath");
while (rscItr.hasNext()) {
linkedResources.add(((Resource)rscItr.next()).getPath());
}
return linkedResources;
}
public Map<String, String> getReferences(String assetPath, ResourceResolver resolver) {
HashMap<String, String> linkedResources = new HashMap<String, String>();
assetPath = this.escapeIllegalXpathSearchChars(assetPath);
String query = "//element(*, nt:unstructured)[@dam:resolvedPath= '" + assetPath + "' or @sling:resource = '" + assetPath + "']";
try {
if (resolver.getResource(assetPath) != null && ((Node)resolver.getResource(assetPath).adaptTo(Node.class)).isNodeType("nt:folder")) {
query = "//element(*, nt:unstructured)[(jcr:like(@dam:resolvedPath, '" + assetPath + "%') or jcr:like(@sling:resource , '" + assetPath + "%'))]";
}
}
catch (RepositoryException e) {
log.debug("error while checking node type in asset reference resolver", (Throwable)e);
}
log.debug("Getting references for the asset {} by executing the query {} ", (Object)assetPath, (Object)query);
Iterator rscItr = resolver.findResources(query, "xpath");
while (rscItr.hasNext()) {
Resource assetNode;
Resource searchedRsc = (Resource)rscItr.next();
if ("granite:Task".equals(ResourceUtil.getValueMap((Resource)searchedRsc).get("jcr:primaryType", (Object)"")) || "cq/gui/components/projects/admin/card/assetlinkcard".equals(searchedRsc.getResourceType())) {
Resource project;
for (project = searchedRsc.getParent(); project != null && project.adaptTo(Project.class) == null; project = project.getParent()) {
}
if (project == null) continue;
linkedResources.put(project.getPath(), searchedRsc.getPath());
continue;
}
String assetNodePath = this.checkCollectionReference(searchedRsc, assetPath);
Resource linkNode = searchedRsc.getParent();
if (assetNodePath != null) {
linkedResources.put(assetNodePath, searchedRsc.getPath());
continue;
}
if (linkNode == null || (assetNode = linkNode.getParent()) == null || !linkNode.getName().equalsIgnoreCase("links") || !assetNode.getResourceType().equalsIgnoreCase("dam:Asset")) continue;
linkedResources.put(assetNode.getPath(), searchedRsc.getPath());
}
return linkedResources;
}
public String createReference(String assetPath, boolean doSave, String resolvedPath, List<Object> data, ResourceResolver resolver) throws RepositoryException {
log.debug("createReference: attempting to resolve the asset to [{}]...", (Object)resolvedPath);
if (data == null || data.size() == 0) {
log.error("createReference: could not create the reference as data is null or empty");
return null;
}
String originalPath = (String)data.get(0);
Resource resource = resolver.getResource(assetPath);
com.adobe.granite.asset.api.Asset graniteAsset = (com.adobe.granite.asset.api.Asset)resource.adaptTo(com.adobe.granite.asset.api.Asset.class);
HashMap<String, String> properties = new HashMap<String, String>();
properties.put("dam:originalPath", originalPath);
if (resolvedPath != null) {
properties.put("dam:resolvedPath", resolvedPath);
} else {
properties.put("dam:resolvedPath", "");
}
String referencePath = null;
if (graniteAsset != null && resolvedPath != null) {
graniteAsset.addRelation("links", resolvedPath, properties);
graniteAsset.listRelations("links");
referencePath = assetPath + "/" + "jcr:content" + "/" + "related" + "/" + "links";
}
return referencePath;
}
public boolean resolveLink(String linkPath, String resolvedPath, ResourceResolver resolver) {
Session session = (Session)resolver.adaptTo(Session.class);
log.debug("reLink: attempting to re link the missing asset at: ", (Object)linkPath);
try {
if (!session.itemExists(linkPath)) {
return false;
}
Node assetNode = (Node)session.getItem(linkPath);
if (resolvedPath != null) {
assetNode.setProperty("dam:resolvedPath", resolvedPath);
}
}
catch (RepositoryException e) {
log.error("Unable to relink the asset : " + e.getMessage(), (Throwable)e);
return false;
}
return true;
}
public boolean deleteLink(String linkPath, ResourceResolver resolver) {
Session session = (Session)resolver.adaptTo(Session.class);
log.debug("deleteLink: attempting to delete the link at :", (Object)linkPath);
try {
if (!session.itemExists(linkPath)) {
return false;
}
Node linkNode = (Node)session.getItem(linkPath);
if (linkNode.hasProperty("dam:resolvedPath")) {
linkNode.setProperty("dam:resolvedPath", "");
}
}
catch (RepositoryException e) {
log.error("Unable to delete the link node: " + e.getMessage(), (Throwable)e);
return false;
}
return true;
}
public boolean cleanup(String assetPath, ResourceResolver resolver) {
log.debug("cleanup: attempting to clean up all the links for the asset :" + assetPath);
Session session = (Session)resolver.adaptTo(Session.class);
Collection<String> linkNodes = this.getReferences(assetPath, resolver).values();
if (linkNodes.size() == 0) {
return false;
}
Iterator<String> linkNodesItr = linkNodes.iterator();
boolean returnFlag = true;
while (linkNodesItr.hasNext()) {
if (this.deleteLink(linkNodesItr.next(), resolver)) continue;
returnFlag = false;
}
try {
session.save();
}
catch (RepositoryException e) {
log.error("cleanUp: Unable to save the session", (Object)e.getMessage(), (Object)e);
}
return returnFlag;
}
private String escapeIllegalXpathSearchChars(String s) {
StringBuffer sb = new StringBuffer();
for (char c : s.toCharArray()) {
if (c == '!' || c == ':' || c == '^' || c == '[' || c == ']' || c == '{' || c == '}' || c == '?' || c == '\"' || c == '\\') {
sb.append('\\');
} else if (c == '\'') {
sb.append(c);
}
sb.append(c);
}
return sb.toString();
}
private String checkCollectionReference(Resource searchedRsc, String originalPath) {
String referredPath = (String)ResourceUtil.getValueMap((Resource)searchedRsc).get("sling:resource", String.class);
if (referredPath.equals(originalPath) || referredPath.indexOf(originalPath + "/") == 0) {
Resource resource;
for (resource = searchedRsc.getParent(); !(resource == null || resource.getResourceType().equalsIgnoreCase("dam:Asset") || resource.getResourceType().equals("dam/collection") || "dam/collection".equals(resource.getResourceSuperType())); resource = resource.getParent()) {
}
if (this.isPagesRelation(searchedRsc, resource)) {
return null;
}
return resource.getPath();
}
return null;
}
private boolean isPagesRelation(Resource searchedRsc, Resource resource) {
return searchedRsc.getPath().contains(resource.getPath() + "/jcr:content/related/" + "pages");
}
}