StandardImageHandler.java 25.9 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.xmp.core.XMPMetadata
 *  com.adobe.xmp.core.serializer.RDFXMLSerializer
 *  com.adobe.xmp.core.serializer.RDFXMLSerializerContext
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.api.Rendition
 *  com.day.cq.dam.api.handler.xmp.XMPHandler
 *  com.day.cq.dam.api.metadata.ExtractedMetadata
 *  javax.jcr.RepositoryException
 *  org.apache.commons.imaging.ImageFormat
 *  org.apache.commons.imaging.ImageFormats
 *  org.apache.commons.imaging.ImageInfo
 *  org.apache.commons.imaging.ImageParser
 *  org.apache.commons.imaging.ImageReadException
 *  org.apache.commons.imaging.Imaging
 *  org.apache.commons.imaging.common.GenericImageMetadata
 *  org.apache.commons.imaging.common.GenericImageMetadata$GenericImageMetadataItem
 *  org.apache.commons.imaging.common.ImageMetadata
 *  org.apache.commons.imaging.common.ImageMetadata$ImageMetadataItem
 *  org.apache.commons.imaging.common.bytesource.ByteSource
 *  org.apache.commons.imaging.common.bytesource.ByteSourceFile
 *  org.apache.commons.imaging.common.bytesource.ByteSourceInputStream
 *  org.apache.commons.imaging.formats.jpeg.JpegImageMetadata
 *  org.apache.commons.imaging.formats.jpeg.JpegPhotoshopMetadata
 *  org.apache.commons.imaging.formats.tiff.TiffField
 *  org.apache.commons.imaging.formats.tiff.TiffImageMetadata
 *  org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants
 *  org.apache.commons.imaging.formats.tiff.fieldtypes.FieldType
 *  org.apache.commons.imaging.formats.tiff.fieldtypes.FieldTypeByte
 *  org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByte
 *  org.apache.commons.io.FileUtils
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.commons.handler;

import com.adobe.xmp.core.XMPMetadata;
import com.adobe.xmp.core.serializer.RDFXMLSerializer;
import com.adobe.xmp.core.serializer.RDFXMLSerializerContext;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.api.Rendition;
import com.day.cq.dam.api.handler.xmp.XMPHandler;
import com.day.cq.dam.api.metadata.ExtractedMetadata;
import com.day.cq.dam.commons.handler.AbstractAssetHandler;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.RepositoryException;
import org.apache.commons.imaging.ImageFormat;
import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageParser;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.common.GenericImageMetadata;
import org.apache.commons.imaging.common.ImageMetadata;
import org.apache.commons.imaging.common.bytesource.ByteSource;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.apache.commons.imaging.common.bytesource.ByteSourceInputStream;
import org.apache.commons.imaging.formats.jpeg.JpegImageMetadata;
import org.apache.commons.imaging.formats.jpeg.JpegPhotoshopMetadata;
import org.apache.commons.imaging.formats.tiff.TiffField;
import org.apache.commons.imaging.formats.tiff.TiffImageMetadata;
import org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants;
import org.apache.commons.imaging.formats.tiff.fieldtypes.FieldType;
import org.apache.commons.imaging.formats.tiff.fieldtypes.FieldTypeByte;
import org.apache.commons.imaging.formats.tiff.taginfos.TagInfoByte;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
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.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(inherit=1, metatype=1)
@Service
public class StandardImageHandler
extends AbstractAssetHandler {
    protected final Logger log = LoggerFactory.getLogger(StandardImageHandler.class);
    public static final String CONFIG_LARGE_FILE_THRESHOLD = "large_file_threshold";
    private static final long DEFAULT_LARGE_FILE_THRESHOLD = -1;
    public static final String CONFIG_LARGE_COMMENT_THRESHOLD = "large_comment_threshold";
    private static final long DEFAULT_LARGE_COMMENT_THRESHOLD = 5000;
    @Property(longValue={-1}, name="large_file_threshold", label="Threshold size to use intermediate temporary file", description="Asset size greater than threshold use temporary file instead of memory buffer to avoid OutOfMemoryError. Value of -1 means that the use of temporary file is disabled.")
    private long largeFileThreshold = -1;
    @Property(longValue={5000}, name="large_comment_threshold", label="Threshold size to skip comments being stored", description="Comment size greater than threshold will not be stored. Value of -1 means that all comments would be stored irrespective of their size.")
    private long largeCommentThreshold = 5000;
    public static final String GIF_MIMETYPE = "image/gif";
    public static final String PNG1_MIMETYPE = "image/png";
    public static final String PNG2_MIMETYPE = "image/x-png";
    public static final String JPEG_MIMETYPE = "image/jpeg";
    public static final String PJPEG_MIMETYPE = "image/pjpeg";
    public static final String TIFF_MIMETYPE = "image/tiff";
    public static final String TIFF1_MIMETYPE = "image/x-tiff";
    public static final String BMP1_MIMETYPE = "image/x-ms-bmp";
    public static final String BMP2_MIMETYPE = "image/bmp";
    public static final String RAW1_MIMETYPE = "image/x-raw-adobe";
    public static final String RAW2_MIMETYPE = "image/x-raw-hasselblad";
    public static final String RAW3_MIMETYPE = "image/x-raw-fuji";
    public static final String RAW4_MIMETYPE = "image/x-raw-canon";
    public static final String RAW5_MIMETYPE = "image/x-raw-kodak";
    public static final String RAW6_MIMETYPE = "image/x-raw-minolta";
    public static final String RAW7_MIMETYPE = "image/x-raw-nikon";
    public static final String RAW8_MIMETYPE = "image/x-raw-olympus";
    public static final String RAW9_MIMETYPE = "image/x-raw-pentax";
    public static final String RAW10_MIMETYPE = "image/x-raw-sony";
    public static final String RAW11_MIMETYPE = "image/x-raw-sigma";
    public static final String RAW12_MIMETYPE = "image/x-raw-epson";
    public static final String RAW13_MIMETYPE = "image/x-raw-mamiya";
    public static final String RAW14_MIMETYPE = "image/x-raw-leaf";
    public static final String RAW15_MIMETYPE = "image/x-raw-panasonic";
    public static final String RAW16_MIMETYPE = "image/x-raw-phaseone";
    public static final String RAW17_MIMETYPE = "image/x-raw-red";
    public static final String RAW18_MIMETYPE = "image/x-raw-imacon";
    public static final String RAW19_MIMETYPE = "image/x-raw-logitech";
    public static final String RAW20_MIMETYPE = "image/x-raw-casio";
    public static final String RAW21_MIMETYPE = "image/x-raw-rawzor";
    public static final String DNG_MIMETYPE = "image/dng";
    protected static final String[] MIME_TYPES = new String[]{"image/gif", "image/png", "image/x-png", "image/tiff", "image/x-tiff", "image/x-ms-bmp", "image/bmp", "image/x-raw-adobe", "image/x-raw-hasselblad", "image/x-raw-fuji", "image/x-raw-canon", "image/x-raw-kodak", "image/x-raw-minolta", "image/x-raw-nikon", "image/x-raw-olympus", "image/x-raw-pentax", "image/x-raw-sony", "image/x-raw-sigma", "image/x-raw-epson", "image/x-raw-mamiya", "image/x-raw-leaf", "image/x-raw-panasonic", "image/x-raw-phaseone", "image/x-raw-red", "image/x-raw-imacon", "image/x-raw-logitech", "image/x-raw-casio", "image/x-raw-rawzor", "image/dng"};
    private static final Set<String> IGNORED_FROM_SANSELAN = new HashSet<String>();
    @Property(boolValue={0})
    protected static final String ENABLE_BINARY_META_EXTRACTION = "cq.dam.enable.ext.meta.extraction";
    protected boolean enableExtMetaExtraction = false;
    @Reference(policy=ReferencePolicy.DYNAMIC, cardinality=ReferenceCardinality.OPTIONAL_UNARY)
    protected XMPHandler xmpHandler;

    protected synchronized void bindXmpHandler(XMPHandler handler) {
        this.xmpHandler = handler;
        this.log.debug("binding xmp handler");
    }

    protected synchronized void unbindXmpHandler(XMPHandler handler) {
        this.xmpHandler = null;
        this.log.debug("un-binding xmp handler");
    }

    public String[] getMimeTypes() {
        return MIME_TYPES;
    }

    public ExtractedMetadata extractMetadata(Asset asset) {
        ExtractedMetadata metadata = new ExtractedMetadata();
        try {
            this.extractMetadata(asset, metadata);
            this.setMimetype(metadata, asset);
        }
        catch (Exception e) {
            this.log.error("extractMetadata: error while extracting metadata for asset [{}]: ", (Object)asset.getPath(), (Object)e);
        }
        return metadata;
    }

    @Override
    public BufferedImage getImage(Rendition rendition) throws IOException {
        return this.getImage(rendition, null);
    }

    /*
     * Exception decompiling
     */
    @Override
    public BufferedImage getImage(Rendition rendition, Dimension maxDimension) throws IOException {
        // This method has failed to decompile.  When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file.
        // java.lang.ClassCastException: org.benf.cfr.reader.bytecode.analysis.parse.statement.Nop cannot be cast to org.benf.cfr.reader.bytecode.analysis.parse.statement.TryStatement
        // org.benf.cfr.reader.bytecode.analysis.parse.utils.finalhelp.FinalAnalyzer.identifyFinally(FinalAnalyzer.java:163)
        // org.benf.cfr.reader.bytecode.analysis.opgraph.op3rewriters.FinallyRewriter.identifyFinally(FinallyRewriter.java:40)
        // org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:483)
        // org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:217)
        // org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:162)
        // org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:95)
        // org.benf.cfr.reader.entities.Method.analyse(Method.java:355)
        // org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:768)
        // org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:700)
        // org.benf.cfr.reader.Main.doJar(Main.java:134)
        // org.benf.cfr.reader.Main.main(Main.java:189)
        throw new IllegalStateException("Decompilation failed");
    }

    private boolean doFileBuffering(Rendition r) {
        return this.largeFileThreshold != -1 && this.largeFileThreshold <= r.getSize();
    }

    private boolean doAddComment(int commentSize) {
        return this.largeCommentThreshold == -1 || this.largeCommentThreshold != -1 && this.largeCommentThreshold >= (long)commentSize;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected Map<String, Serializable> extractImageInfo(Asset asset) {
        HashMap<String, Serializable> metadata = new HashMap<String, Serializable>();
        InputStream is = asset.getOriginal().getStream();
        File tempFile = null;
        FileOutputStream fos = null;
        try {
            ByteSourceInputStream bs = null;
            if (this.doFileBuffering(asset.getOriginal())) {
                tempFile = File.createTempFile("asset", ".tmp");
                fos = new FileOutputStream(tempFile);
                IOUtils.copy((InputStream)is, (OutputStream)fos);
                bs = new ByteSourceFile(tempFile);
            } else {
                bs = new ByteSourceInputStream(is, null);
            }
            ImageParser imageParser = this.getImageParser((ByteSource)bs);
            this.extractImageInfo(asset.getPath(), (ByteSource)bs, imageParser);
        }
        catch (ImageReadException e) {
            this.log.warn("extractImageInfo: error while reading metadata from image [{}]: ", (Object)asset.getPath(), (Object)e);
        }
        catch (IOException e) {
            this.log.warn("extractImageInfo: error while reading info from image [{}]: ", (Object)asset.getPath(), (Object)e);
        }
        finally {
            IOUtils.closeQuietly((OutputStream)fos);
            FileUtils.deleteQuietly((File)tempFile);
            IOUtils.closeQuietly((InputStream)is);
        }
        return metadata;
    }

    private Map<String, Serializable> extractImageInfo(String path, ByteSource bsis, ImageParser ip) {
        HashMap<String, Serializable> metadata = new HashMap<String, Serializable>();
        try {
            ImageInfo imageInfo = ip.getImageInfo(bsis);
            int numberOfImages = imageInfo.getNumberOfImages();
            if (numberOfImages < 0) {
                numberOfImages = 1;
            }
            metadata.put("File format", (Serializable)((Object)imageInfo.getFormat().getName()));
            metadata.put("MIME type", (Serializable)((Object)imageInfo.getMimeType()));
            metadata.put("Image Width", (Integer)imageInfo.getWidth());
            metadata.put("Image Length", (Integer)imageInfo.getHeight());
            metadata.put("Bits per pixel", (Integer)imageInfo.getBitsPerPixel());
            metadata.put("Progressive", (Serializable)((Object)(imageInfo.isProgressive() ? "yes" : "no")));
            metadata.put("Number of images", (Integer)numberOfImages);
            metadata.put("Physical width in dpi", (Integer)imageInfo.getPhysicalWidthDpi());
            metadata.put("Physical height in dpi", (Integer)imageInfo.getPhysicalHeightDpi());
            metadata.put("Physical width in inches", Double.valueOf(imageInfo.getPhysicalWidthInch()));
            metadata.put("Physical height in inches", Double.valueOf(imageInfo.getPhysicalHeightInch()));
            List comments = imageInfo.getComments();
            int numComments = comments == null ? 0 : comments.size();
            int commentsStored = 0;
            if (numComments > 0) {
                StringBuffer buffer = new StringBuffer();
                for (int i = 0; i < numComments; ++i) {
                    if (comments == null || !this.doAddComment(((String)comments.get(i)).length())) continue;
                    buffer.append((String)comments.get(i)).append('\n');
                    ++commentsStored;
                }
                metadata.put("Comments", (Serializable)((Object)buffer.toString()));
            }
            metadata.put("Number of textual comments", (Integer)commentsStored);
        }
        catch (ImageReadException e) {
            this.log.warn("extractImageInfo: error while reading metadata from image [{}]: ", (Object)path, (Object)e);
        }
        catch (IOException e) {
            this.log.warn("extractImageInfo: error while reading info from image [{}]: ", (Object)path, (Object)e);
        }
        return metadata;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void extractMetadata(Asset asset, ExtractedMetadata metadata) throws IOException, ImageReadException {
        InputStream is = asset.getOriginal().getStream();
        ImageMetadata data = null;
        File tempFile = null;
        try {
            ByteSourceInputStream bs;
            block31 : {
                bs = null;
                FileOutputStream fos = null;
                ImageParser imageParser = null;
                try {
                    if (this.doFileBuffering(asset.getOriginal())) {
                        tempFile = File.createTempFile("asset", ".tmp");
                        fos = new FileOutputStream(tempFile);
                        IOUtils.copy((InputStream)is, (OutputStream)fos);
                        bs = new ByteSourceFile(tempFile);
                    } else {
                        bs = new ByteSourceInputStream(is, null);
                    }
                    imageParser = this.getImageParser((ByteSource)bs);
                    data = imageParser.getMetadata((ByteSource)bs);
                    if (data != null && data instanceof JpegImageMetadata) {
                        JpegImageMetadata jpegMetadata = (JpegImageMetadata)data;
                        JpegPhotoshopMetadata jpegphotoshopMetadata = jpegMetadata.getPhotoshop();
                        if (jpegphotoshopMetadata != null) {
                            for (ImageMetadata.ImageMetadataItem item : jpegphotoshopMetadata.getItems()) {
                                this.setPhotoshopItemValue(item, metadata);
                            }
                        }
                        data = jpegMetadata.getExif();
                    }
                    Map<String, Serializable> imageData = this.extractImageInfo(asset.getPath(), (ByteSource)bs, imageParser);
                    metadata.addMetadataProperties(imageData);
                    if (data != null && data instanceof TiffImageMetadata) {
                        TiffImageMetadata tiffMetadata = (TiffImageMetadata)data;
                        List allFields = tiffMetadata.getAllFields();
                        for (TiffField tf : allFields) {
                            if (tf.getDirectoryType() == 1) continue;
                            String tagName = tf.getTagName();
                            FieldType fieldType = tf.getFieldType();
                            if (!(!this.enableExtMetaExtraction && (fieldType.equals((Object)FieldType.BYTE) || fieldType.equals((Object)FieldType.UNDEFINED)) || tagName.equals(TiffTagConstants.TIFF_TAG_XMP.name) || IGNORED_FROM_SANSELAN.contains(tagName))) {
                                this.log.debug("name =" + tagName + ", type=" + tf.getFieldTypeName());
                                metadata.setMetaDataProperty(tagName, this.trimValue(tf));
                                continue;
                            }
                            this.log.debug("Skipping XMP tag [" + tagName + "],  of type [" + fieldType.getName() + "] XMP is scanned by CQ generic XMP scanner", (Object)tagName);
                        }
                    }
                }
                catch (Exception e) {
                    Map<String, Serializable> imageDimensionData;
                    this.log.warn("extractMetadata: cannot read metadata from image [{}]: ", (Object)asset.getPath(), (Object)e);
                    if (e instanceof ImageReadException && bs != null && imageParser != null && !(imageDimensionData = this.getDimensionMetadata(asset.getPath(), (ByteSource)bs, imageParser)).isEmpty()) {
                        metadata.addMetadataProperties(imageDimensionData);
                    }
                }
                finally {
                    IOUtils.closeQuietly((OutputStream)fos);
                }
                if (this.enableExtMetaExtraction) {
                    this.extractImageXMP((ByteSource)bs, metadata);
                }
                if (this.xmpHandler != null) {
                    ByteArrayInputStream xmps = null;
                    try {
                        XMPMetadata xmpMetadata = this.xmpHandler.readXmpMetadata(asset);
                        if (xmpMetadata != null) {
                            byte[] xmpBytes = new RDFXMLSerializer().serializeToBuffer(xmpMetadata, (Map)new RDFXMLSerializerContext());
                            xmps = new ByteArrayInputStream(xmpBytes);
                            metadata.setXmp((InputStream)xmps);
                        }
                        break block31;
                    }
                    catch (Exception e) {
                        if (this.log.isDebugEnabled()) {
                            this.log.error("Couldn't extract metadata using XMPhandler, attempting brute-force extraction", (Throwable)e);
                        } else {
                            this.log.warn("Couldn't extract metadata using XMPhandler, attempting brute-force extraction");
                        }
                        this.execGenericProcessor(asset.getOriginal().getStream(), metadata);
                    }
                    finally {
                        IOUtils.closeQuietly((InputStream)xmps);
                    }
                }
                this.execGenericProcessor(asset.getOriginal().getStream(), metadata);
            }
            if (metadata.getXmp() == null && !this.enableExtMetaExtraction) {
                this.extractImageXMP((ByteSource)bs, metadata);
            }
        }
        catch (Exception e) {
            this.log.warn("extractMetadata: cannot read metadata from image [{}]: ", (Object)asset.getPath(), (Object)e);
        }
        finally {
            FileUtils.deleteQuietly((File)tempFile);
            IOUtils.closeQuietly((InputStream)is);
        }
    }

    private Map<String, Serializable> getDimensionMetadata(String path, ByteSource bsis, ImageParser ip) {
        HashMap<String, Serializable> metadata = new HashMap<String, Serializable>();
        try {
            Dimension d = ip.getImageSize(bsis, null);
            if (d != null) {
                metadata.put("Image Width", (Integer)((int)d.getWidth()));
                metadata.put("Image Length", (Integer)((int)d.getHeight()));
            }
        }
        catch (ImageReadException e) {
            this.log.warn("getDimensionMetadata - imageParser.getImageSize() fallback attempt: error while reading metadata from image [{}]: ", (Object)path, (Object)e);
        }
        catch (IOException e) {
            this.log.warn("getDimensionMetadata - imageParser.getImageSize() fallback attempt: error while reading info from image [{}]: ", (Object)path, (Object)e);
        }
        return metadata;
    }

    private void extractImageXMP(ByteSource bs, ExtractedMetadata metadata) {
        try {
            String xmpStr = Imaging.getXmpXml((ByteSource)bs, (Map)null);
            this.log.debug("extracted xmp string is {}", (Object)xmpStr);
            if (xmpStr != null) {
                metadata.setXmp((InputStream)new ByteArrayInputStream(xmpStr.getBytes("utf-8")));
            }
        }
        catch (Exception e) {
            this.log.error("could not extract XMP from the image", (Throwable)e);
        }
    }

    private void setPhotoshopItemValue(ImageMetadata.ImageMetadataItem item, ExtractedMetadata extractedMetadata) {
        if (item instanceof GenericImageMetadata.GenericImageMetadataItem) {
            GenericImageMetadata.GenericImageMetadataItem imageItem = (GenericImageMetadata.GenericImageMetadataItem)item;
            String keyword = imageItem.getKeyword();
            String text = imageItem.getText();
            Object existingVal = extractedMetadata.getMetaDataProperty(keyword);
            if (existingVal != null) {
                if (existingVal instanceof String) {
                    ArrayList<String> newVal = new ArrayList<String>();
                    newVal.add((String)existingVal);
                    newVal.add(text);
                    extractedMetadata.setMetaDataProperty(keyword, newVal);
                } else if (existingVal instanceof List) {
                    ((List)existingVal).add(text);
                }
            } else {
                extractedMetadata.setMetaDataProperty(keyword, (Object)text);
            }
        }
    }

    private ImageParser getImageParser(ByteSource byteSrc) throws ImageReadException, IOException {
        ImageFormat format = Imaging.guessFormat((ByteSource)byteSrc);
        if (!format.equals((Object)ImageFormats.UNKNOWN)) {
            ImageParser[] imageParsers;
            for (ImageParser imageParser : imageParsers = ImageParser.getAllImageParsers()) {
                if (!imageParser.canAcceptType(format)) continue;
                return imageParser;
            }
        }
        throw new ImageReadException("Can't parse this format.");
    }

    private Object trimValue(TiffField field) throws ImageReadException {
        Object fieldValue = field.getValue();
        if (fieldValue instanceof String) {
            fieldValue = StringUtils.trimToEmpty((String)fieldValue.toString());
        }
        return fieldValue;
    }

    private boolean isPng(Rendition rendition) {
        return rendition.getMimeType().startsWith("image/png") || rendition.getMimeType().startsWith("image/x-png");
    }

    private boolean isGif(Rendition rendition) {
        return rendition.getMimeType().startsWith("image/gif");
    }

    private boolean isRaw(Rendition rendition) {
        return rendition.getMimeType().startsWith("image/x-raw-");
    }

    @Activate
    protected void activate(ComponentContext context) throws RepositoryException {
        this.enableExtMetaExtraction = PropertiesUtil.toBoolean(context.getProperties().get("cq.dam.enable.ext.meta.extraction"), (boolean)false);
        this.largeFileThreshold = PropertiesUtil.toLong(context.getProperties().get("large_file_threshold"), (long)-1);
        this.largeCommentThreshold = PropertiesUtil.toLong(context.getProperties().get("large_comment_threshold"), (long)5000);
    }

    static {
        IGNORED_FROM_SANSELAN.add("Image Description");
        IGNORED_FROM_SANSELAN.add("Artist");
        IGNORED_FROM_SANSELAN.add("Copyright");
    }
}