UIHelper.java 16.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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.LabeledResource
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.Rendition
 *  com.day.cq.i18n.I18n
 *  com.day.cq.wcm.api.Page
 *  com.day.text.Text
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.ValueFormatException
 *  javax.jcr.security.AccessControlManager
 *  javax.jcr.security.Privilege
 *  javax.servlet.http.HttpServletRequest
 *  org.apache.commons.lang.ArrayUtils
 *  org.apache.commons.lang.StringUtils
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.request.RequestPathInfo
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ValueMap
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.commons.util;

import com.day.cq.commons.LabeledResource;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.commons.util.DamUtil;
import com.day.cq.i18n.I18n;
import com.day.cq.wcm.api.Page;
import com.day.text.Text;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.ValueFormatException;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UIHelper {
    private static final Logger log = LoggerFactory.getLogger(UIHelper.class);
    private static final String[] LAYER_UNSUPPORTED_MIME_TYPES = new String[]{"image/tiff"};
    private static final List<String> LAYER_UNSUPPORTED_MIME_TYPE = Arrays.asList(LAYER_UNSUPPORTED_MIME_TYPES);
    private static final Pattern renditionPattern = Pattern.compile("cq5dam\\.(.*)?\\.(\\d+)\\.(\\d+)\\.(.*)");
    private static final int PATTERN_WIDTH_INDEX = 2;
    private static final int PATTERN_HEIGHT_INDEX = 3;

    private static boolean isLayerUnSupported(String mimetype) {
        return LAYER_UNSUPPORTED_MIME_TYPE.contains(mimetype);
    }

    public static String getTitle(Resource res) {
        String title = null;
        try {
            Node resNode = (Node)res.adaptTo(Node.class);
            if (null != resNode && resNode.isNodeType("dam:Asset")) {
                Node metadata = resNode.getNode("jcr:content/metadata");
                if (metadata != null && metadata.hasProperty("dc:title")) {
                    title = DamUtil.getValue(metadata, "dc:title", "");
                }
            } else if (null != resNode && resNode.isNodeType("cq:Page")) {
                Node contentNode;
                Page page = (Page)res.adaptTo(Page.class);
                title = page.getPageTitle();
                if (StringUtils.isBlank((String)title) && resNode.hasNode("jcr:content") && (contentNode = resNode.getNode("jcr:content")).hasProperty("jcr:title")) {
                    title = contentNode.getProperty("jcr:title").getString();
                }
            } else {
                LabeledResource lr = (LabeledResource)res.adaptTo(LabeledResource.class);
                if (lr != null) {
                    title = lr.getTitle();
                } else if (null != resNode && resNode.hasProperty("jcr:title")) {
                    title = resNode.getProperty("jcr:title").getString();
                }
            }
        }
        catch (Exception ex) {
            log.error("error in get title ", (Throwable)ex);
        }
        if (title != null && !title.equals("")) {
            return title;
        }
        return Text.getName((String)res.getPath());
    }

    public static Rendition getBestfitRendition(Asset asset, int width) {
        List renditions = asset.getRenditions();
        return DamUtil.getBestFitRendition(width, renditions);
    }

    public static long getCacheKiller(Node node) {
        long ck = 0;
        try {
            if (node.isNodeType("dam:Asset") || node.isNodeType("nt:file")) {
                if (node.hasProperty("jcr:content/jcr:lastModified")) {
                    ck = node.getProperty("jcr:content/jcr:lastModified").getLong();
                }
            } else if (node.isNodeType("nt:folder")) {
                if (node.hasProperty("jcr:content/folderThumbnail/jcr:content/jcr:lastModified")) {
                    ck = node.getProperty("jcr:content/folderThumbnail/jcr:content/jcr:lastModified").getLong();
                }
            } else if (node.hasProperty("jcr:lastModified")) {
                ck = node.getProperty("jcr:lastModified").getLong();
            }
        }
        catch (Exception e) {
            log.error("error creating cache killer", (Throwable)e);
        }
        return ck / 1000 * 1000;
    }

    public static Resource getCurrentSuffixResource(SlingHttpServletRequest request) {
        String contentPath = request.getRequestPathInfo().getSuffix();
        Resource res = request.getResourceResolver().getResource(contentPath);
        if (contentPath == null || !contentPath.contains("/content/dam") || res == null) {
            return request.getResourceResolver().getResource("/content/dam");
        }
        return res;
    }

    public static String getSizeLabel(double size) {
        String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int i = 0;
        while (size >= 1024.0) {
            size /= 1024.0;
            ++i;
        }
        return "" + (double)Math.round(size * Math.pow(10.0, 1.0)) / Math.pow(10.0, 1.0) + " " + units[i];
    }

    public static String getSizeLabel(double size, SlingHttpServletRequest slingRequest) {
        Locale locale = slingRequest.getResourceBundle(null).getLocale();
        I18n i18n = new I18n((HttpServletRequest)slingRequest);
        int i = 0;
        while (size >= 1024.0) {
            size /= 1024.0;
            ++i;
        }
        NumberFormat nf = NumberFormat.getInstance(locale);
        String formattedSize = nf.format((double)Math.round(size * Math.pow(10.0, 1.0)) / Math.pow(10.0, 1.0));
        switch (i) {
            case 0: {
                return i18n.get("{0} B", "Byte", new Object[]{formattedSize});
            }
            case 1: {
                return i18n.get("{0} KB", "KiloByte", new Object[]{formattedSize});
            }
            case 2: {
                return i18n.get("{0} MB", "MegaByte", new Object[]{formattedSize});
            }
            case 3: {
                return i18n.get("{0} GB", "GigaByte", new Object[]{formattedSize});
            }
            case 4: {
                return i18n.get("{0} TB", "TeraByte", new Object[]{formattedSize});
            }
        }
        return "";
    }

    public static String getResolutionLabel(long width, long height, SlingHttpServletRequest slingRequest) {
        Locale locale = slingRequest.getResourceBundle(null).getLocale();
        I18n i18n = new I18n((HttpServletRequest)slingRequest);
        NumberFormat nf = NumberFormat.getInstance(locale);
        String formattedWidth = nf.format(width);
        String formattedHeight = nf.format(height);
        return i18n.get("{0} x {1}", "width x height, image resolution", new Object[]{formattedWidth, formattedHeight});
    }

    public static boolean hasPermission(AccessControlManager acm, Resource res, String privilege) throws RepositoryException {
        Privilege p = acm.privilegeFromName(privilege);
        return acm.hasPrivileges(res.getPath(), new Privilege[]{p});
    }

    public static Privilege[] getAllPermission(AccessControlManager acm, Resource res) throws PathNotFoundException, RepositoryException {
        return acm.getPrivileges(res.getPath());
    }

    public static boolean isEditSupportedFormat(String mimetype) {
        String[] supportedTypes;
        for (String type : supportedTypes = new String[]{"image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp"}) {
            if (!type.equalsIgnoreCase(mimetype)) continue;
            return true;
        }
        return false;
    }

    public static Rendition getBestFitRendtionBasedOnSize(Asset asset, long size) {
        return UIHelper.getBestFitRendtionBasedOnSize(asset, size, false);
    }

    public static Rendition getBestFitRendtionBasedOnSize(Asset asset, long size, boolean preferOriginal) {
        try {
            Rendition bestFit;
            long sizeinBytes = size * 1024;
            List renditions = asset.getRenditions();
            SizeBasedRenditionComparator comp = new SizeBasedRenditionComparator();
            Collections.sort(renditions, comp);
            Iterator itr = renditions.iterator();
            bestFit = null;
            while (itr.hasNext()) {
                Rendition rend = (Rendition)itr.next();
                if (!UIHelper.canRenderOnWeb(rend.getMimeType()) || rend.getSize() > sizeinBytes) continue;
                bestFit = rend;
            }
            if (bestFit == null) {
                for (Rendition rend : renditions) {
                    if (!UIHelper.canRenderOnWeb(rend.getMimeType())) continue;
                    bestFit = rend;
                    break;
                }
            } else if (preferOriginal && UIHelper.canRenderOnWeb(asset.getOriginal().getMimeType()) && bestFit.getSize() > asset.getOriginal().getSize()) {
                return asset.getOriginal();
            }
            return bestFit;
        }
        catch (Exception e) {
            log.error("Error occured while getting best fit rendition ", (Throwable)e);
            return null;
        }
    }

    public static boolean canRenderOnWeb(String mimeType) {
        return mimeType != null && (mimeType.toLowerCase().contains("jpeg") || mimeType.toLowerCase().contains("jpg") || mimeType.toLowerCase().contains("gif") || mimeType.toLowerCase().contains("png"));
    }

    public static int getWidth(Rendition r) {
        return UIHelper.getDimension(r, "tiff:ImageWidth");
    }

    public static int getHeight(Rendition r) {
        return UIHelper.getDimension(r, "tiff:ImageLength");
    }

    private static int getDimension(Rendition r, String dimensionProperty) {
        if (r == null) {
            log.debug("Null rendition at", (Throwable)new Exception("Null rendition"));
            return 0;
        }
        if (dimensionProperty == null || !dimensionProperty.equals("tiff:ImageLength") && !dimensionProperty.equals("tiff:ImageWidth")) {
            log.warn("Incorrect dimension property for {}", (Object)r.getPath(), (Object)new Exception("Invalid property name " + dimensionProperty));
            return 0;
        }
        String name = r.getName();
        if (name == null) {
            log.warn("Null name returned at {}", (Object)r.getPath());
            return 0;
        }
        try {
            if (name.equals("original")) {
                Asset asset = (Asset)r.adaptTo(Asset.class);
                if (asset == null) {
                    log.debug("Rendition at {} is not adaptable to an asset.", (Object)r.getPath());
                    return 0;
                }
                String val = asset.getMetadataValue(dimensionProperty);
                if (val == null || val.length() == 0) {
                    log.debug("Unable to find metadata property {} for {}", (Object)dimensionProperty, (Object)asset.getPath());
                    return 0;
                }
                try {
                    return Integer.parseInt(val);
                }
                catch (NumberFormatException nfe) {
                    log.warn("Metadata property {} was {} and not a number at {}", new Object[]{dimensionProperty, val, asset.getPath()});
                    return 0;
                }
            }
            Matcher matcher = renditionPattern.matcher(name);
            if (matcher.matches()) {
                int matcherIndex = "tiff:ImageLength".equals(dimensionProperty) ? 3 : 2;
                int renditionHeight = Integer.parseInt(matcher.group(matcherIndex));
                return renditionHeight;
            }
            log.info("Unknown naming format for name {} at {}", (Object)name, (Object)r.getPath());
            return 0;
        }
        catch (Exception e) {
            log.warn("Unexpected exception finding dimension for asset at {} " + r.getPath(), (Throwable)e);
            return 0;
        }
    }

    @Deprecated
    public static String lookupMimeType(String mimeType, Node node, boolean uppercase) {
        try {
            if (node == null || mimeType == null) {
                return null;
            }
            mimeType = mimeType.toUpperCase();
            NodeIterator it = node.getNodes();
            while (it.hasNext()) {
                int end;
                Node child = it.nextNode();
                String list = child.getProperty("mimetypes").getString();
                if (list == null) continue;
                list = list.replaceAll("\\s", "");
                int ind = (list = list.toUpperCase()).indexOf(mimeType);
                if (ind == -1 || ind != 0 && (ind - 1 < 0 || list.charAt(ind - 1) != ',') || list.charAt(end = ind + mimeType.length()) != ',' && list.charAt(end) != ';') continue;
                if (uppercase) {
                    return child.getProperty("jcr:description").getString();
                }
                return child.getProperty("jcr:title").getString();
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static String lookupMimeType(String mimeType, Resource resource, boolean uppercase) {
        try {
            if (resource == null || mimeType == null) {
                return null;
            }
            Iterator it = resource.listChildren();
            while (it.hasNext()) {
                Resource child = (Resource)it.next();
                ValueMap childVM = (ValueMap)child.adaptTo(ValueMap.class);
                String mimetypes = (String)childVM.get("mimetypes", String.class);
                Object[] mimetypesList = mimetypes.split(",");
                if (!ArrayUtils.contains((Object[])mimetypesList, (Object)mimeType.toUpperCase())) continue;
                if (uppercase) {
                    return (String)childVM.get("jcr:description", String.class);
                }
                return (String)childVM.get("jcr:title", String.class);
            }
        }
        catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static boolean isCheckedOutByDrive(Asset asset) {
        try {
            Node assetNode = (Node)asset.adaptTo(Node.class);
            Node jcrContent = assetNode.getNode("jcr:content");
            if (jcrContent != null && jcrContent.hasProperty("cq:drivelock")) {
                return true;
            }
        }
        catch (PathNotFoundException e) {
            log.warn("Asset does not exists ", (Throwable)e);
        }
        catch (RepositoryException e) {
            log.warn("Respoitory execption", (Throwable)e);
        }
        return false;
    }

    public static String getCheckedOutby(Asset asset) {
        if (UIHelper.isCheckedOutByDrive(asset)) {
            try {
                Node assetNode = (Node)asset.adaptTo(Node.class);
                Node jcrContent = assetNode.getNode("jcr:content");
                return jcrContent.getProperty("cq:drivelock").getString();
            }
            catch (PathNotFoundException e) {
                log.warn("Asset does not exists ", (Throwable)e);
            }
            catch (ValueFormatException e) {
                log.warn("Value format exception ", (Throwable)e);
            }
            catch (RepositoryException e) {
                log.warn("Respoitory execption", (Throwable)e);
            }
        }
        return "";
    }

    private static class SizeBasedRenditionComparator
    implements Comparator<Rendition> {
        private SizeBasedRenditionComparator() {
        }

        @Override
        public int compare(Rendition r1, Rendition r2) {
            if (r1.getSize() < r2.getSize()) {
                return -1;
            }
            if (r1.getSize() == r2.getSize()) {
                return 0;
            }
            return 1;
        }
    }

}