AssetImpl.java 19.7 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.asset.api.Asset
 *  com.adobe.granite.asset.api.AssetException
 *  com.adobe.granite.asset.api.AssetMetadata
 *  com.adobe.granite.asset.api.Rendition
 *  com.adobe.xmp.XMPException
 *  com.adobe.xmp.XMPIterator
 *  com.adobe.xmp.XMPMeta
 *  com.adobe.xmp.XMPMetaFactory
 *  com.adobe.xmp.options.IteratorOptions
 *  com.adobe.xmp.options.PropertyOptions
 *  com.adobe.xmp.path.XMPPath
 *  com.adobe.xmp.path.XMPPathParser
 *  com.adobe.xmp.path.XMPPathParserException
 *  com.adobe.xmp.properties.XMPPropertyInfo
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.AssetManager
 *  com.day.cq.dam.api.Rendition
 *  com.day.cq.dam.api.RenditionPicker
 *  com.day.cq.dam.api.Revision
 *  com.day.cq.dam.commons.metadata.SimpleXmpToJcrMetadataBuilder
 *  com.day.cq.dam.commons.util.DamUtil
 *  javax.jcr.NamespaceException
 *  javax.jcr.NamespaceRegistry
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  org.apache.commons.lang.StringUtils
 *  org.apache.sling.api.adapter.SlingAdaptable
 *  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.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.core.impl;

import com.adobe.granite.asset.api.AssetException;
import com.adobe.granite.asset.api.AssetMetadata;
import com.adobe.xmp.XMPException;
import com.adobe.xmp.XMPIterator;
import com.adobe.xmp.XMPMeta;
import com.adobe.xmp.XMPMetaFactory;
import com.adobe.xmp.options.IteratorOptions;
import com.adobe.xmp.options.PropertyOptions;
import com.adobe.xmp.path.XMPPath;
import com.adobe.xmp.path.XMPPathParser;
import com.adobe.xmp.path.XMPPathParserException;
import com.adobe.xmp.properties.XMPPropertyInfo;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.AssetManager;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.api.RenditionPicker;
import com.day.cq.dam.api.Revision;
import com.day.cq.dam.commons.metadata.SimpleXmpToJcrMetadataBuilder;
import com.day.cq.dam.commons.util.DamUtil;
import com.day.cq.dam.core.impl.AssetIDProvider;
import com.day.cq.dam.core.impl.RenditionImpl;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.adapter.SlingAdaptable;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AssetImpl
extends SlingAdaptable
implements Asset {
    private static final Logger log = LoggerFactory.getLogger(AssetImpl.class);
    public static final String RESOURCE_TYPE = "dam:Asset";
    private final Resource resource;
    private final ResourceResolver resolver;
    private final Resource metadataResource;
    private final AssetManager assetManager;
    private final AssetIDProvider idProvider;
    private boolean batchMode = false;
    private com.adobe.granite.asset.api.Asset graniteAsset;

    public AssetImpl(Resource resource, AssetIDProvider assetIDProvider) {
        this.resource = resource;
        this.resolver = resource.getResourceResolver();
        this.graniteAsset = (com.adobe.granite.asset.api.Asset)resource.adaptTo(com.adobe.granite.asset.api.Asset.class);
        if (this.graniteAsset == null) {
            throw new IllegalStateException("Cannot adapt Resource to a Granite Asset, resource: " + resource.getPath());
        }
        this.assetManager = (AssetManager)this.resolver.adaptTo(AssetManager.class);
        this.idProvider = assetIDProvider;
        this.metadataResource = this.resolver.getResource(resource, "jcr:content/metadata");
    }

    public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
        if (type == Resource.class) {
            return (AdapterType)this.resource;
        }
        if (type == ResourceResolver.class) {
            return (AdapterType)this.resolver;
        }
        if (type == AssetManager.class) {
            return (AdapterType)this.assetManager;
        }
        if (type == Node.class) {
            return (AdapterType)this.resource.adaptTo(Node.class);
        }
        if (type == com.adobe.granite.asset.api.Asset.class) {
            return (AdapterType)this.resource.adaptTo(com.adobe.granite.asset.api.Asset.class);
        }
        return (AdapterType)super.adaptTo(type);
    }

    public String getPath() {
        return this.resource.getPath();
    }

    public String getName() {
        return ResourceUtil.getName((Resource)this.resource);
    }

    public String getMetadataValue(String name) {
        return this.getMetadataValue(name, true);
    }

    public String getMetadataValueFromJcr(String name) {
        return this.getMetadataValue(name, false);
    }

    /*
     * Enabled force condition propagation
     * Lifted jumps to return sites
     */
    private String getMetadataValue(String name, boolean parseXmp) {
        if (name.indexOf(":") <= 0) return "";
        if (null != this.metadataResource) {
            try {
                Node metadataNode = (Node)this.metadataResource.adaptTo(Node.class);
                if (metadataNode.hasProperty(name)) {
                    return DamUtil.getValue((Node)metadataNode, (String)name, (String)"");
                }
                if (!parseXmp) return "";
                return (String)this.graniteAsset.getAssetMetadata().getProperty(XMPPathParser.parse((String)name, this.getPrefixMap(name)), String.class);
            }
            catch (RepositoryException e) {
                log.error("getMetadataValue: repository error while getting metadata value with key [{}] for asset [" + this.getPath() + "]: ", (Object)name, (Object)e);
                return "";
            }
            catch (XMPPathParserException e) {
                log.error("getxmppath: XMP error while getting [{}] for asset [" + this.getPath() + "]: ", (Object)name, (Object)e);
                return "";
            }
        } else {
            log.warn("getMetadataValue: metadata node does not exist for asset [{}], cannot get value for key [{}].", (Object)this.getPath(), (Object)name);
        }
        return "";
    }

    public long getLastModified() {
        Calendar mod = (Calendar)this.getGraniteAssetProperties().get("jcr:lastModified", Calendar.class);
        return null != mod ? mod.getTimeInMillis() : 0;
    }

    public Rendition getRendition(String name) {
        com.adobe.granite.asset.api.Rendition r = this.getGraniteAsset().getRendition(name);
        return null != r ? (Rendition)r.adaptTo(Rendition.class) : null;
    }

    public Rendition getImagePreviewRendition() {
        String[] renditions;
        for (String preview : renditions = new String[]{"cqdam.preview.tiff", "cqdam.preview.png", "cqdam.preview.jpg", "thumbnail.jpg", "original"}) {
            Rendition r = this.getRendition(preview);
            if (r == null) continue;
            return r;
        }
        return null;
    }

    public Rendition getOriginal() {
        return this.getRendition("original");
    }

    @Deprecated
    public Rendition getCurrentOriginal() {
        Rendition currentOriginal = null;
        String currentOriginalName = (String)this.getGraniteAssetProperties().get("currentOriginal", (Object)"");
        if (StringUtils.isNotBlank((String)currentOriginalName) && null == (currentOriginal = this.getRendition(currentOriginalName))) {
            log.warn("getCurrentOriginal: current original name [{}] points to non-existing rendition for asset [{}].", (Object)currentOriginalName, (Object)this.getPath());
        }
        return null != currentOriginal ? currentOriginal : this.getOriginal();
    }

    public boolean isSubAsset() {
        return DamUtil.isSubAsset((Resource)this.resource);
    }

    public Object getMetadata(String name) {
        Map<String, Object> metadata = this.getMetadata();
        if (metadata.containsKey(name)) {
            return metadata.get(name);
        }
        log.debug("getMetadata: metadata map doesn't contain value with key [{}] for asset [{}].", (Object)name, (Object)this.getPath());
        return null;
    }

    public Map<String, Object> getMetadata() {
        HashMap<String, Object> metadata = new HashMap<String, Object>();
        if (null == this.metadataResource) {
            log.warn("asset [{}] is missing metadata node.", (Object)this.getPath());
            return metadata;
        }
        try {
            SimpleXmpToJcrMetadataBuilder metadataAdapter = new SimpleXmpToJcrMetadataBuilder();
            XMPMeta meta = metadataAdapter.getXmpFromJcr((Node)this.metadataResource.adaptTo(Node.class));
            for (XMPPropertyInfo prop : meta) {
                if (prop.getOptions().isSchemaNode()) continue;
                if (prop.getOptions().isArray()) {
                    String name = prop.getPath();
                    XMPIterator aItr = meta.iterator(prop.getNamespace(), name, new IteratorOptions().setJustChildren(true));
                    ArrayList<Object> aList = new ArrayList<Object>();
                    while (aItr.hasNext()) {
                        XMPPropertyInfo aprop = (XMPPropertyInfo)aItr.next();
                        if (!aprop.getOptions().isSimple() || "".equals(aprop.getOriValue())) continue;
                        aList.add(aprop.getOriValue());
                    }
                    name = prop.getPath().indexOf("/") >= 0 ? prop.getPath().substring(prop.getPath().lastIndexOf("/") + 1) : prop.getPath();
                    metadata.put(name, aList.toArray(new Object[aList.size()]));
                    continue;
                }
                if (prop.getOptions().isStruct()) {
                    log.debug("Not able to process the node [{}] as Struct type is not supported", (Object)prop.getPath());
                    continue;
                }
                if (!prop.getOptions().isQualifier() && !prop.getOptions().isSimple() || prop.getPath().endsWith("]")) continue;
                Object val = prop.getOriValue();
                String name = prop.getPath().indexOf("/") >= 0 ? prop.getPath().substring(prop.getPath().lastIndexOf("/") + 1) : prop.getPath();
                metadata.put(name, val);
            }
        }
        catch (XMPException e) {
            log.error("getMetadata: XMP error while getting metadata for asset [{}]: ", (Object)this.getPath(), (Object)e);
        }
        catch (RepositoryException e) {
            log.error("getMetadata: XMP error while getting metadata for asset [{}]: ", (Object)this.getPath(), (Object)e);
        }
        return metadata;
    }

    @Deprecated
    public Resource setRendition(String name, InputStream is, String mimeType) {
        Rendition rendition = this.addRendition(name, is, mimeType);
        return null != rendition ? (Resource)rendition.adaptTo(Resource.class) : null;
    }

    @Deprecated
    public void setCurrentOriginal(String name) {
        try {
            this.getGraniteAssetProperties().put((Object)"currentOriginal", (Object)name);
            this.saveAsset();
        }
        catch (AssetException e) {
            log.error("setCurrentOriginal: error while setting rendition [{}] as current original for asset [{}]: ", (Object)this.getPath(), (Object)e);
        }
    }

    public Revision createRevision(String label, String comment) throws Exception {
        return this.assetManager.createRevision((Asset)this, label, comment);
    }

    public List<Rendition> getRenditions() {
        ArrayList<Rendition> renditions = new ArrayList<Rendition>();
        Iterator<Rendition> resources = this.listRenditions();
        while (resources.hasNext()) {
            renditions.add(resources.next());
        }
        return renditions;
    }

    public Iterator<Rendition> listRenditions() {
        final Iterator graniteRenditionIterator = this.getGraniteAsset().listRenditions();
        return new Iterator<Rendition>(){

            @Override
            public void remove() {
                graniteRenditionIterator.remove();
            }

            @Override
            public Rendition next() {
                com.adobe.granite.asset.api.Rendition graniteRendition = (com.adobe.granite.asset.api.Rendition)graniteRenditionIterator.next();
                return new RenditionImpl((Resource)graniteRendition);
            }

            @Override
            public boolean hasNext() {
                return graniteRenditionIterator.hasNext();
            }
        };
    }

    public Rendition getRendition(RenditionPicker picker) {
        return picker.getRendition((Asset)this);
    }

    public String getModifier() {
        return (String)this.getGraniteAssetProperties().get("jcr:lastModifiedBy", (Object)"");
    }

    public Asset restore(String revisionId) throws Exception {
        return this.assetManager.restore(revisionId);
    }

    public Collection<Revision> getRevisions(Calendar cal) throws Exception {
        return this.assetManager.getRevisions(this.getPath(), cal);
    }

    public String getMimeType() {
        Rendition original;
        String mimeType = this.getMetadataValue("dc:format");
        if (StringUtils.isBlank((String)mimeType) && null != (original = this.getOriginal())) {
            mimeType = original.getMimeType();
        }
        return StringUtils.isNotBlank((String)mimeType) ? mimeType : null;
    }

    public Rendition addRendition(String name, InputStream is, String mimeType) {
        HashMap<String, Object> rhMap = new HashMap<String, Object>();
        rhMap.put("rendition.mime", mimeType);
        return this.addRendition(name, is, rhMap);
    }

    public Rendition addRendition(String name, InputStream is, Map<String, Object> map) {
        try {
            com.adobe.granite.asset.api.Rendition graniteRendition = this.getGraniteAsset().setRendition(name, is, map);
            AssetImpl.touch(this.resource);
            AssetImpl.touch((Resource)graniteRendition);
            if (this.saveAsset()) {
                return new RenditionImpl((Resource)graniteRendition);
            }
            return null;
        }
        catch (AssetException e) {
            log.error("addRendition: cannot add new rendition [{}] for asset [" + this.getPath() + "]: ", (Object)name, (Object)e);
            return null;
        }
        catch (RepositoryException e) {
            log.error("addRendition: cannot update lastModified for  new rendition [{}] for asset [" + this.getPath() + "]: ", (Object)name, (Object)e);
            return null;
        }
    }

    public Asset addSubAsset(String name, String mimeType, InputStream stream) {
        String path = this.getPath() + "/" + "subassets" + "/" + name;
        return this.assetManager.createAsset(path, stream, mimeType, !this.isBatchMode());
    }

    public Collection<Asset> getSubAssets() {
        LinkedList<Asset> assets = new LinkedList<Asset>();
        Resource subAssetsFolder = this.resolver.getResource(this.resource, "subassets");
        if (null != subAssetsFolder) {
            Iterator resources = this.resolver.listChildren(subAssetsFolder);
            while (resources.hasNext()) {
                Asset a = (Asset)((Resource)resources.next()).adaptTo(Asset.class);
                if (null == a) continue;
                assets.add(a);
            }
        } else {
            log.debug("getSubAssets: couldn't get sub-assets, as the [{}] folder doesn't exist for asset [{}]", (Object)"subassets", (Object)this.getPath());
        }
        return assets;
    }

    public void removeRendition(String name) {
        try {
            this.getGraniteAsset().removeRendition(name);
            this.saveAsset();
        }
        catch (AssetException e) {
            log.error("removeRendition: error while removing rendition [{}] of asset [" + this.getPath() + "]", (Object)name, (Object)e);
        }
    }

    public void setBatchMode(boolean enabled) {
        this.batchMode = enabled;
    }

    public boolean isBatchMode() {
        return this.batchMode;
    }

    public String getID() {
        String assetID = "";
        try {
            assetID = this.idProvider.getAssetID(this);
        }
        catch (RepositoryException e) {
            log.error("Couldn't obtain Asset ID for asset at {}Please see if jcr:uuid exists", (Object)this.getPath(), (Object)e);
            assetID = "";
        }
        return assetID;
    }

    private boolean saveAsset() {
        if (!this.isBatchMode()) {
            Session session = (Session)this.resolver.adaptTo(Session.class);
            try {
                session.save();
            }
            catch (RepositoryException e) {
                log.error("saveAsset: error while saving asset [{}]: ", (Object)this.getPath(), (Object)e);
                try {
                    session.refresh(false);
                }
                catch (RepositoryException e1) {
                    log.error("saveAsset: error while reverting changes after failed save for asset [{}]: ", (Object)this.getPath(), (Object)e1);
                }
                return false;
            }
        }
        return true;
    }

    public static void touch(Resource resource) throws RepositoryException {
        AssetImpl.touch((Node)resource.adaptTo(Node.class));
    }

    public static void touch(Node node) throws RepositoryException {
        if (node != null && node.hasNode("jcr:content")) {
            node = node.getNode("jcr:content");
            node.setProperty("jcr:lastModified", Calendar.getInstance());
            node.setProperty("jcr:lastModifiedBy", node.getSession().getUserID());
        }
    }

    private com.adobe.granite.asset.api.Asset getGraniteAsset() {
        return this.graniteAsset;
    }

    private ValueMap getGraniteAssetProperties() {
        return (ValueMap)this.graniteAsset.adaptTo(ValueMap.class);
    }

    private Map<String, String> getPrefixMap(String name) {
        HashMap<String, String> prefixMap = new HashMap<String, String>();
        if (name.indexOf(58) > 0) {
            try {
                String prefix = StringUtils.substringBefore((String)name, (String)":");
                String nsUri = XMPMetaFactory.getSchemaRegistry().getNamespaceURI(prefix);
                if (StringUtils.isBlank((String)nsUri)) {
                    Session session = (Session)this.metadataResource.getResourceResolver().adaptTo(Session.class);
                    nsUri = session.getWorkspace().getNamespaceRegistry().getURI(prefix);
                    if (StringUtils.isNotBlank((String)nsUri)) {
                        XMPMetaFactory.getSchemaRegistry().registerNamespace(nsUri, prefix);
                    } else {
                        log.warn("Asset {} does not have the property {} or its namespace is not registered", (Object)this.getPath(), (Object)name);
                    }
                }
                prefixMap.put(prefix, nsUri);
            }
            catch (XMPException e) {
                log.debug("getPrefixMap: error while getting prefix map", (Throwable)e);
            }
            catch (NamespaceException e) {
                log.debug("getPrefixMap: error while getting prefix map", (Throwable)e);
            }
            catch (RepositoryException e) {
                log.debug("getPrefixMap: error while getting prefix map", (Throwable)e);
            }
        }
        return prefixMap;
    }

}