Java Examples for com.day.cq.dam.api.Asset

The following java examples will help you to understand the usage of com.day.cq.dam.api.Asset. These source code samples are taken from different open source projects.

Example 1
Project: ease-master  File: AssetIndexer.java View source code
@Override
public void indexData(Map<String, Object> data, Resource resource, String containerPath) {
    Asset asset = resource.adaptTo(Asset.class);
    if (asset != null) {
        data.put(IndexFields.PATH, asset.getPath());
        Object tagsArr = asset.getMetadata(NameConstants.PN_TAGS);
        if (tagsArr != null && tagsArr instanceof Object[]) {
            Object[] tags = (Object[]) tagsArr;
            for (Object tag : tags) {
                putMultiValue(data, IndexFields.TAGS, tag.toString());
            }
        }
        String title = StringUtils.trimToNull((String) asset.getMetadataValue("dc:title"));
        if (title == null || title.trim().length() == 0) {
            title = asset.getName();
        }
        data.put(IndexFields.TITLE, title);
    }
}
Example 2
Project: acs-aem-commons-master  File: NamedTransformImageServlet.java View source code
/**
     * Intelligently determines how to find the Image based on the associated SlingRequest.
     *
     * @param request the SlingRequest Obj
     * @return the Image object configured w the info of where the image to render is stored in CRX
     */
protected final Image resolveImage(final SlingHttpServletRequest request) {
    final Resource resource = request.getResource();
    final ResourceResolver resourceResolver = request.getResourceResolver();
    final PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
    final Page page = pageManager.getContainingPage(resource);
    if (DamUtil.isAsset(resource)) {
        // For assets, pick the configured rendition if it exists
        // If rendition does not exist, use original
        final Asset asset = DamUtil.resolveToAsset(resource);
        Rendition rendition = asset.getRendition(renditionPatternPicker);
        if (rendition == null) {
            log.warn("Could not find rendition [ {} ] for [ {} ]", renditionPatternPicker.toString(), resource.getPath());
            rendition = asset.getOriginal();
        }
        final Resource renditionResource = request.getResourceResolver().getResource(rendition.getPath());
        final Image image = new Image(resource);
        image.set(Image.PN_REFERENCE, renditionResource.getPath());
        return image;
    } else if (DamUtil.isRendition(resource) || resourceResolver.isResourceType(resource, JcrConstants.NT_FILE) || resourceResolver.isResourceType(resource, JcrConstants.NT_RESOURCE)) {
        // For renditions; use the requested rendition
        final Image image = new Image(resource);
        image.set(Image.PN_REFERENCE, resource.getPath());
        return image;
    } else if (page != null) {
        if (resourceResolver.isResourceType(resource, NameConstants.NT_PAGE) || StringUtils.equals(resource.getPath(), page.getContentResource().getPath())) {
            // Is a Page or Page's Content Resource; use the Page's image resource
            return new Image(page.getContentResource(), NAME_IMAGE);
        } else {
            return new Image(resource);
        }
    } else {
        if (resourceResolver.isResourceType(resource, RT_LOCAL_SOCIAL_IMAGE) && resource.getValueMap().get("mimetype", StringUtils.EMPTY).startsWith("image/")) {
            // Is a UGC image
            return new SocialImageImpl(resource, NAME_IMAGE);
        } else if (resourceResolver.isResourceType(resource, RT_REMOTE_SOCIAL_IMAGE)) {
            // Is a UGC image
            return new SocialRemoteImageImpl(resource, NAME_IMAGE);
        }
    }
    return new Image(resource);
}
Example 3
Project: aem-samples-master  File: ReferencedAssetsServlet.java View source code
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    try {
        JSONObject jsonOut = new JSONObject();
        Node jcrNode = request.getResource().adaptTo(Node.class);
        if (jcrNode == null) {
            // every adaptTo() can return null, so let's handle that case here 
            // although it's very unlikely
            LOG.error("cannot adapt resource {} to a node", request.getResource().getPath());
            response.getOutputStream().print(new JSONObject().toString());
            return;
        }
        // let's use the specialized assetReferenceSearch, which does all the work for us
        AssetReferenceSearch search = new AssetReferenceSearch(jcrNode, DAM_ROOT, request.getResourceResolver());
        Map<String, Asset> result = search.search();
        for (String key : result.keySet()) {
            Asset asset = result.get(key);
            JSONObject assetDetails = new JSONObject();
            assetDetails.put("path", asset.getPath());
            assetDetails.put("mimetype", asset.getMimeType());
            jsonOut.put(asset.getName(), assetDetails);
        }
        response.getOutputStream().print(jsonOut.toString(2));
    } catch (JSONException e) {
        LOG.error("Cannot serialize JSON", e);
        response.getOutputStream().print(new JSONObject().toString());
    }
}
Example 4
Project: com.activecq.samples-master  File: ContentFinderHitBuilder.java View source code
/**
     * @param hit
     * @param map
     * @return
     * @throws RepositoryException
     */
private static Map<String, Object> addAssetData(final Hit hit, Map<String, Object> map) throws RepositoryException {
    final Resource resource = hit.getResource();
    final Asset asset = DamUtil.resolveToAsset(resource);
    String title = resource.getName();
    if (StringUtils.isNotBlank(asset.getMetadataValue(DamConstants.DC_TITLE))) {
        title = asset.getMetadataValue(DamConstants.DC_TITLE);
    }
    map.put("title", title);
    map.put("lastModified", getLastModified(asset));
    map.put("mimeType", asset.getMimeType());
    map.put("size", getSize(asset));
    map.put("ck", getCK(asset));
    map.put("type", "Asset");
    return map;
}
Example 5
Project: jackalope-master  File: NodeResourceImpl.java View source code
@Override
@SuppressWarnings({ "unchecked", "deprecation" })
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if (type.equals(Node.class))
        return (AdapterType) node;
    if (type.equals(ValueMap.class) || type.equals(Map.class))
        return (AdapterType) new JcrPropertyMap(node);
    if (type.equals(PersistableValueMap.class))
        return (AdapterType) new JcrModifiablePropertyMap(node);
    if (type.equals(ModifiableValueMap.class))
        return (AdapterType) new JcrModifiableValueMap(node, null);
    if (type.equals(Page.class)) {
        try {
            ValueMap properties = this.adaptTo(ValueMap.class);
            if (properties == null)
                return null;
            String primaryType = properties.get(JCR_PRIMARYTYPE, String.class);
            if (primaryType == null || !primaryType.equals(JcrConstants.CQ_PAGE))
                return null;
            if (!node.hasNode(JCR_CONTENT))
                return null;
            return (AdapterType) new PageImpl(new NodeResourceImpl(resourceResolver, node));
        } catch (RepositoryException e) {
            return null;
        }
    }
    if (type.equals(Asset.class)) {
        try {
            ValueMap properties = ResourceUtil.getValueMap(this);
            return !"dam:Asset".equals(properties.get(JCR_PRIMARYTYPE, String.class)) ? null : !node.hasNode(JCR_CONTENT) ? null : (AdapterType) new AssetImpl(this);
        } catch (RepositoryException e) {
            return null;
        }
    }
    if (type.equals(InputStream.class)) {
        try {
            Node content = node.isNodeType(NT_FILE) ? node.getNode(JCR_CONTENT) : node;
            Property data = content.hasProperty(JCR_DATA) ? content.getProperty(JCR_DATA) : null;
            return data != null ? (AdapterType) data.getBinary().getStream() : null;
        } catch (RepositoryException e) {
            return null;
        }
    }
    return super.adaptTo(type);
}
Example 6
Project: acs-aem-tools-master  File: CsvAssetImporterServlet.java View source code
@Override
protected final void doPost(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    final JSONObject jsonResponse = new JSONObject();
    final Parameters params = new Parameters(request);
    if (params.getFile() != null) {
        final long start = System.currentTimeMillis();
        final Iterator<String[]> rows = this.getRowsFromCsv(params);
        try {
            // First row is property names
            // Get the required properties for this tool (source and dest)
            final String[] requiredProperties = new String[] { //params.getRelSrcPathProperty(),
            params.getAbsTargetPathProperty() };
            // Get the columns from the first row of the CSV
            final Map<String, Column> columns = Column.getColumns(rows.next(), params.getMultiDelimiter(), params.getIgnoreProperties(), requiredProperties);
            // Process Asset row entries
            final List<String> result = new ArrayList<String>();
            final List<String> batch = new ArrayList<String>();
            final List<String> failures = new ArrayList<String>();
            log.info(params.toString());
            request.getResourceResolver().adaptTo(Session.class).getWorkspace().getObservationManager().setUserData("acs-aem-tools.csv-asset-importer");
            while (rows.hasNext()) {
                final String[] row = rows.next();
                log.debug("Processing row {}", Arrays.asList(row));
                try {
                    if (!this.isSkippedRow(params, columns, row)) {
                        batch.add(this.importAsset(request.getResourceResolver(), params, columns, row));
                    }
                } catch (FileNotFoundException e) {
                    failures.add(row[columns.get(params.getAbsTargetPathProperty()).getIndex()]);
                    log.error("Could not find file for row ", Arrays.asList(row), e);
                } catch (CsvAssetImportException e) {
                    failures.add(row[columns.get(params.getAbsTargetPathProperty()).getIndex()]);
                    log.error("Could not import the row due to ", e.getMessage(), e);
                }
                log.debug("Processed row {}", Arrays.asList(row));
                if (batch.size() % params.getBatchSize() == 0) {
                    this.save(request.getResourceResolver(), batch.size());
                    result.addAll(batch);
                    batch.clear();
                    // Throttle saves
                    if (params.getThrottle() > 0) {
                        log.info("Throttling CSV Asset Importer batch processing for {} ms", params.getThrottle());
                        Thread.sleep(params.getThrottle());
                    }
                }
            }
            // Final save to catch any non-modulo stragglers; will only invoke persist if there are changes
            this.save(request.getResourceResolver(), batch.size());
            result.addAll(batch);
            if (log.isInfoEnabled()) {
                log.info("Imported as TOTAL of [ {} ] assets in {} ms", result.size(), System.currentTimeMillis() - start);
            }
            try {
                jsonResponse.put("assets", result);
                jsonResponse.put("failures", failures);
            } catch (JSONException e) {
                log.error("Could not serialized Excel Importer results into JSON", e);
                this.addMessage(jsonResponse, "Could not serialized Excel Importer results into JSON");
                response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (RepositoryException e) {
            log.error("Could not save Assets to JCR", e);
            this.addMessage(jsonResponse, "Could not save assets. " + e.getMessage());
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            log.error("Could not process CSV import", e);
            this.addMessage(jsonResponse, "Could not process CSV import. " + e.getMessage());
            response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        log.error("Could not find CSV file in request.");
        this.addMessage(jsonResponse, "CSV file is missing");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    response.getWriter().print(jsonResponse.toString());
}
Example 7
Project: Slice-CQ56-master  File: DamModule.java View source code
@Provides
public Asset getAsset(@Nullable Resource resource) {
    if (null != resource) {
        return resource.adaptTo(Asset.class);
    }
    return null;
}
Example 8
Project: Slice-CQ55-master  File: DamModule.java View source code
@Provides
public Asset getAsset(@Nullable Resource resource) {
    if (null != resource) {
        return resource.adaptTo(Asset.class);
    }
    return null;
}