AssetMoveEventHandler.java 19 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.s7dam.set.SwatchSet
 *  com.day.cq.dam.commons.util.DamUtil
 *  com.day.cq.search.PredicateGroup
 *  com.day.cq.search.Query
 *  com.day.cq.search.QueryBuilder
 *  com.day.cq.search.result.SearchResult
 *  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.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.NonExistingResource
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.event.jobs.Job
 *  org.apache.sling.event.jobs.consumer.JobConsumer
 *  org.apache.sling.event.jobs.consumer.JobConsumer$JobResult
 *  org.apache.sling.resource.collection.ResourceCollection
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.core.impl;

import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.s7dam.set.SwatchSet;
import com.day.cq.dam.commons.util.DamUtil;
import com.day.cq.dam.core.impl.ui.preview.FolderPreviewUpdater;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.SearchResult;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.Node;
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.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.consumer.JobConsumer;
import org.apache.sling.resource.collection.ResourceCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, immediate=1)
@Service(value={JobConsumer.class})
@Property(name="job.topics", value={"com/adobe/cq/dam/assetmove"})
public class AssetMoveEventHandler
implements JobConsumer {
    private static final Logger logger = LoggerFactory.getLogger(AssetMoveEventHandler.class);
    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 DAM_ORIG_PATH = "dam:originalPath";
    private static final String DAM_RES_PATH = "dam:resolvedPath";
    private static final String DAM_ASSET_RELATIVE_PATH = "dam:relativePath";
    private static final String CONTENT_DAM = "/content/dam";
    private static final String SUBSERVICE = "assetmove";
    private static final Map<String, Object> AUTH_INFO = Collections.singletonMap("sling.service.subservice", "assetmove");
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private QueryBuilder queryBuilder;
    @Reference
    private FolderPreviewUpdater folderPreviewUpdater;

    private void updateFolderThumbnail(ResourceResolver resolver, String path, String eventType, String assetNewPath) {
        NonExistingResource assetResource = new NonExistingResource(resolver, path);
        Resource parentFolderResource = assetResource.getParent();
        if (parentFolderResource == null) {
            return;
        }
        Node parentFolderNode = (Node)parentFolderResource.adaptTo(Node.class);
        if (parentFolderNode == null) {
            return;
        }
        boolean success = this.folderPreviewUpdater.initiateFolderPreviewUpdate(path);
        if (!success) {
            logger.error("Folder thumbnail update couldn't be initiated for ", (Object)path);
        }
        if (eventType.equals("move") && !(success = this.folderPreviewUpdater.initiateFolderPreviewUpdate(assetNewPath))) {
            logger.error("Folder thumbnail update couldn't be initiated for ", (Object)assetNewPath);
        }
    }

    private String getTenantHomeForDeletedResource(ResourceResolver resolver, String path) {
        NonExistingResource nonExistingResource = new NonExistingResource(resolver, path);
        return DamUtil.getTenantAssetsRoot((Resource)nonExistingResource);
    }

    private void updateAssetPath(ResourceResolver resolver, Session session, String path, String eventType, String folderPath, String nodeType) throws PersistenceException, RepositoryException {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("path", this.getTenantHomeForDeletedResource(resolver, path));
        map.put("property", "sling:resource");
        if (nodeType.equals("dam:Asset")) {
            map.put("property.value", path);
        } else {
            map.put("property.value", path + "%");
            map.put("property.operation", "like");
        }
        map.put("type", "nt:unstructured");
        map.put("p.limit", "0");
        Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), session);
        SearchResult results = query.getResult();
        List<Resource> imagesetEntries = this.getSearchResultResources(results);
        for (Resource imagesetEntry : imagesetEntries) {
            ValueMap imagesetEntryProps;
            String assetOldPath;
            ResourceCollection collection = this.findCollection(imagesetEntry);
            if (collection == null || !(assetOldPath = (String)(imagesetEntryProps = ResourceUtil.getValueMap((Resource)imagesetEntry)).get("sling:resource", String.class)).equals(path) && assetOldPath.indexOf(path + "/") != 0) continue;
            NonExistingResource removedResource = new NonExistingResource(resolver, assetOldPath);
            Asset imagesetAsset = this.findAsset(imagesetEntry);
            if (eventType.equals("move")) {
                String assetNewPath = folderPath + assetOldPath.substring(path.length());
                this.updateReferences(collection, imagesetAsset, (Resource)removedResource, assetNewPath);
                Resource modified = resolver.getResource(assetNewPath);
                this.replace(resolver, collection, imagesetAsset, (Resource)removedResource, modified);
                continue;
            }
            collection.remove((Resource)removedResource);
            this.updateLastModified(resolver, collection, imagesetAsset);
        }
        session.save();
    }

    private List<Resource> getSearchResultResources(SearchResult results) {
        ArrayList<Resource> list = new ArrayList<Resource>((int)results.getTotalMatches());
        Iterator i = results.getResources();
        while (i.hasNext()) {
            Resource rr = (Resource)i.next();
            if (rr == null) continue;
            list.add(rr);
        }
        return list;
    }

    private boolean isDamAsset(ResourceResolver resolver, String folderPath) {
        Resource resource = resolver.getResource(folderPath);
        if (resource != null) {
            boolean isAsset = resource.adaptTo(Asset.class) != null;
            boolean hasRelatedPages = resource.getChild("jcr:content/related/pages") != null;
            return isAsset && !hasRelatedPages;
        }
        return false;
    }

    private void updateSwatchPath(ResourceResolver resolver, Session session, String path, String eventType, String assetNewPath) throws RepositoryException {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("path", this.getTenantHomeForDeletedResource(resolver, path));
        map.put("property", "dam:s7Swatch");
        map.put("property.value", path);
        map.put("type", "nt:unstructured");
        map.put("p.limit", "0");
        Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), session);
        SearchResult results = query.getResult();
        List<Resource> imagesetEntries = this.getSearchResultResources(results);
        for (Resource imagesetEntry : imagesetEntries) {
            ModifiableValueMap vm = (ModifiableValueMap)imagesetEntry.adaptTo(ModifiableValueMap.class);
            String assetRef = (String)vm.get("sling:resource", (Object)"");
            if (StringUtils.isBlank((String)assetRef)) {
                logger.warn("swatch {} ref {} found, but asset Ref is missing ", (Object)path, (Object)imagesetEntry);
                continue;
            }
            Resource assetRefRes = resolver.getResource(assetRef);
            if (assetRefRes == null) {
                logger.warn("swatch {} ref {} found, but referenced asset is null", (Object)path, (Object)imagesetEntry);
                continue;
            }
            Asset refAsset = (Asset)assetRefRes.adaptTo(Asset.class);
            Asset imagesetAsset = this.findAsset(imagesetEntry);
            if (imagesetAsset == null) {
                logger.warn("swatch {} ref {} found, but parent asset missing ", (Object)path, (Object)imagesetEntry);
                continue;
            }
            SwatchSet imageset = (SwatchSet)((Resource)imagesetAsset.adaptTo(Resource.class)).adaptTo(SwatchSet.class);
            if (eventType.equals("move")) {
                Resource modified = resolver.getResource(assetNewPath);
                if (modified != null) {
                    imageset.setSwatch(refAsset, (Asset)modified.adaptTo(Asset.class));
                    continue;
                }
                imageset.setSwatch(refAsset, null);
                continue;
            }
            imageset.setSwatch(refAsset, null);
        }
        session.save();
    }

    private Asset findAsset(Resource assetRefResource) {
        return DamUtil.resolveToAsset((Resource)assetRefResource);
    }

    private ResourceCollection findCollection(Resource res) {
        if (res != null) {
            ResourceCollection rc = (ResourceCollection)res.adaptTo(ResourceCollection.class);
            if (rc != null) {
                return rc;
            }
            if (res.getParent() != null) {
                return this.findCollection(res.getParent());
            }
        }
        return null;
    }

    private void replace(ResourceResolver resolver, ResourceCollection collection, Asset imagesetAsset, Resource oldAsset, Resource newAsset) throws PersistenceException {
        if (!collection.contains(oldAsset)) {
            return;
        }
        HashMap props = new HashMap();
        ModifiableValueMap vm = collection.getProperties(oldAsset);
        if (vm != null) {
            props.putAll(vm);
        }
        if (collection.add(newAsset, props)) {
            collection.orderBefore(newAsset, oldAsset);
            collection.remove(oldAsset);
            this.updateLastModified(resolver, collection, imagesetAsset);
        } else {
            logger.warn("failed to add modified {} resource to collection {}", (Object)newAsset.getPath(), (Object)collection.getPath());
        }
    }

    private void updateLastModified(ResourceResolver resolver, ResourceCollection collection, Asset imagesetAsset) {
        Resource res;
        if (imagesetAsset != null) {
            Resource assetRes = (Resource)imagesetAsset.adaptTo(Resource.class);
            res = assetRes.getChild("jcr:content");
        } else {
            res = resolver.getResource(collection.getPath());
        }
        if (res != null) {
            ModifiableValueMap contentProps = (ModifiableValueMap)res.adaptTo(ModifiableValueMap.class);
            contentProps.put((Object)"jcr:lastModifiedBy", (Object)resolver.getUserID());
            contentProps.put((Object)"jcr:lastModified", (Object)Calendar.getInstance());
        }
    }

    private void updateReferences(ResourceCollection collection, Asset imagesetAsset, Resource existing, String assetNewPath) {
        if (!collection.contains(existing)) {
            return;
        }
        ModifiableValueMap props = collection.getProperties(existing);
        if (props != null && props.containsKey((Object)"dam:resolvedPath") && props.containsKey((Object)"dam:originalPath")) {
            String oldOrigPath = props.get((Object)"dam:originalPath").toString();
            String oldResPath = props.get((Object)"dam:resolvedPath").toString();
            props.put((Object)"dam:resolvedPath", (Object)assetNewPath);
            String resOrigPath = this.resolveOriginalPath(oldOrigPath, oldResPath, assetNewPath);
            if (resOrigPath != null) {
                props.put((Object)"dam:originalPath", (Object)resOrigPath);
                if (imagesetAsset != null && DamUtil.checkforAIFile((Asset)imagesetAsset)) {
                    this.updAIXmpManifest((Resource)imagesetAsset.adaptTo(Resource.class), oldOrigPath, resOrigPath);
                }
            }
        }
    }

    private String resolveOriginalPath(String origPath, String resPath, String assetNewPath) {
        if (origPath == null || resPath == null) {
            return null;
        }
        String suffix = resPath.substring("/content/dam".length());
        if (origPath.contains(suffix)) {
            String prefix = origPath.substring(0, origPath.indexOf(suffix));
            if (assetNewPath.length() > "/content/dam".length()) {
                return prefix + assetNewPath.substring("/content/dam".length());
            }
        }
        return null;
    }

    private void updateRelativePath(ResourceResolver resolver, Session session, String eventType, String assetNewPath) {
        if (eventType.equals("move")) {
            try {
                String assetsRoot = DamUtil.getTenantAssetsRoot((ResourceResolver)resolver, (String)assetNewPath);
                int idx = -1;
                idx = assetNewPath.indexOf(assetsRoot);
                if (0 <= idx) {
                    idx += assetsRoot.length();
                }
                Node assetJcrContent = session.getNode(assetNewPath).getNode("jcr:content");
                assetJcrContent.setProperty("dam:relativePath", assetNewPath.substring(idx + 1));
                session.save();
            }
            catch (Exception ign) {
                logger.warn("Couldn't update moved asset node", (Throwable)ign);
            }
        }
    }

    private void updAIXmpManifest(Resource resource, String oldOrigPath, String resOrigPath) {
        Resource linkNode;
        if (resource == null || resource.getChild("jcr:content/metadata/xmpMM:Manifest") == null) {
            return;
        }
        int linkNo = 1;
        do {
            String filePath;
            String property;
            ModifiableValueMap props;
            if ((linkNode = resource.getChild(property = "jcr:content/metadata/xmpMM:Manifest/" + String.valueOf(linkNo) + "/" + "stMfs:reference")) != null && (filePath = (String)(props = (ModifiableValueMap)linkNode.adaptTo(ModifiableValueMap.class)).get("stRef:filePath", String.class)) != null && filePath.equals(oldOrigPath)) {
                props.put((Object)"stRef:filePath", (Object)resOrigPath);
                return;
            }
            ++linkNo;
        } while (linkNode != null);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public JobConsumer.JobResult process(Job job) {
        ResourceResolver resolver = null;
        Session session = null;
        Object totalObj = job.getProperty("assets.total");
        int total = totalObj instanceof Long ? ((Long)totalObj).intValue() : ((Integer)totalObj).intValue();
        try {
            resolver = this.resolverFactory.getServiceResourceResolver(AUTH_INFO);
            session = (Session)resolver.adaptTo(Session.class);
            for (int i = 1; i < total + 1; ++i) {
                String path = (String)job.getProperty("" + i + "_path");
                String eventType = (String)job.getProperty("" + i + "_type");
                String assetNewPath = (String)job.getProperty("" + i + "_new_path");
                if (path.equals(assetNewPath)) continue;
                this.updateAssetPath(resolver, session, path, eventType, assetNewPath, (String)job.getProperty("node_type"));
                this.updateSwatchPath(resolver, session, path, eventType, assetNewPath);
                this.updateFolderThumbnail(resolver, path, eventType, assetNewPath);
                this.updateRelativePath(resolver, session, eventType, assetNewPath);
            }
        }
        catch (PersistenceException e) {
            logger.error("error occurred in updating collection/imageset: ", (Throwable)e);
            JobConsumer.JobResult path = JobConsumer.JobResult.FAILED;
            return path;
        }
        catch (RepositoryException e) {
            logger.error("error occurred in updating collection/imageset: ", (Throwable)e);
            JobConsumer.JobResult path = JobConsumer.JobResult.FAILED;
            return path;
        }
        catch (LoginException e) {
            logger.error("error occurred in updating collection/imageset: ", (Throwable)e);
            JobConsumer.JobResult path = JobConsumer.JobResult.FAILED;
            return path;
        }
        finally {
            if (session != null) {
                session.logout();
            }
            if (resolver != null) {
                resolver.close();
            }
        }
        return JobConsumer.JobResult.OK;
    }

    protected void bindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        this.resolverFactory = resourceResolverFactory;
    }

    protected void unbindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.resolverFactory == resourceResolverFactory) {
            this.resolverFactory = null;
        }
    }

    protected void bindQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
    }

    protected void unbindQueryBuilder(QueryBuilder queryBuilder) {
        if (this.queryBuilder == queryBuilder) {
            this.queryBuilder = null;
        }
    }

    protected void bindFolderPreviewUpdater(FolderPreviewUpdater folderPreviewUpdater) {
        this.folderPreviewUpdater = folderPreviewUpdater;
    }

    protected void unbindFolderPreviewUpdater(FolderPreviewUpdater folderPreviewUpdater) {
        if (this.folderPreviewUpdater == folderPreviewUpdater) {
            this.folderPreviewUpdater = null;
        }
    }
}