    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one
    003 * or more contributor license agreements.  See the NOTICE file
    004 * distributed with this work for additional information
    005 * regarding copyright ownership.  The ASF licenses this file
    006 * to you under the Apache License, Version 2.0 (the
    007 * "License"); you may not use this file except in compliance
    008 * with the License.  You may obtain a copy of the License at
    009 *
    010 * http://www.apache.org/licenses/LICENSE-2.0
    011 *
    012 * Unless required by applicable law or agreed to in writing,
    013 * software distributed under the License is distributed on an
    014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    015 * KIND, either express or implied.  See the License for the
    016 * specific language governing permissions and limitations
    017 * under the License.
    018 */
    019package org.apache.commons.compress.compressors.lzma;
    020
    021import java.util.HashMap;
    022import java.util.Map;
    023
    024import org.apache.commons.compress.compressors.FileNameUtil;
    025import org.apache.commons.compress.utils.OsgiUtils;
    026
    027/**
    028 * Utility code for the lzma compression format.
    029 * @ThreadSafe
    030 * @since 1.10
    031 */
    032public class LZMAUtils {
    033
    034    enum CachedAvailability {
    035        DONT_CACHE, CACHED_AVAILABLE, CACHED_UNAVAILABLE
    036    }
    037
    038    private static final FileNameUtil fileNameUtil;
    039
    040    /**
    041     * LZMA Header Magic Bytes begin a LZMA file.
    042     */
    043    private static final byte[] HEADER_MAGIC = {
    044        (byte) 0x5D, 0, 0
    045    };
    046
    047    private static volatile CachedAvailability cachedLZMAAvailability;
    048
    049    static {
    050        final Map<String, String> uncompressSuffix = new HashMap<>();
    051        uncompressSuffix.put(".lzma", "");
    052        uncompressSuffix.put("-lzma", "");
    053        fileNameUtil = new FileNameUtil(uncompressSuffix, ".lzma");
    054        cachedLZMAAvailability = CachedAvailability.DONT_CACHE;
    055        setCacheLZMAAvailablity(!OsgiUtils.isRunningInOsgiEnvironment());
    056    }
    057
    058    // only exists to support unit tests
    059    static CachedAvailability getCachedLZMAAvailability() {
    060        return cachedLZMAAvailability;
    061    }
    062
    063    /**
    064     * Maps the given file name to the name that the file should have after
    065     * compression with lzma.
    066     *
    067     * @param fileName name of a file
    068     * @return name of the corresponding compressed file
    069     */
    070    public static String getCompressedFilename(final String fileName) {
    071        return fileNameUtil.getCompressedFilename(fileName);
    072    }
    073
    074    /**
    075     * Maps the given name of a lzma-compressed file to the name that
    076     * the file should have after uncompression.  Any file names with
    077     * the generic ".lzma" suffix (or any other generic lzma suffix)
    078     * is mapped to a name without that suffix. If no lzma suffix is
    079     * detected, then the file name is returned unmapped.
    080     *
    081     * @param fileName name of a file
    082     * @return name of the corresponding uncompressed file
    083     */
    084    public static String getUncompressedFilename(final String fileName) {
    085        return fileNameUtil.getUncompressedFilename(fileName);
    086    }
    087
    088    private static boolean internalIsLZMACompressionAvailable() {
    089        try {
    090            LZMACompressorInputStream.matches(null, 0);
    091            return true;
    092        } catch (final NoClassDefFoundError error) { // NOSONAR
    093            return false;
    094        }
    095    }
    096
    097    /**
    098     * Detects common lzma suffixes in the given file name.
    099     *
    100     * @param fileName name of a file
    101     * @return {@code true} if the file name has a common lzma suffix,
    102     *         {@code false} otherwise
    103     */
    104    public static boolean isCompressedFilename(final String fileName) {
    105        return fileNameUtil.isCompressedFilename(fileName);
    106    }
    107
    108    /**
    109     * Are the classes required to support LZMA compression available?
    110     * @return true if the classes required to support LZMA
    111     * compression are available
    112     */
    113    public static boolean isLZMACompressionAvailable() {
    114        final CachedAvailability cachedResult = cachedLZMAAvailability;
    115        if (cachedResult != CachedAvailability.DONT_CACHE) {
    116            return cachedResult == CachedAvailability.CACHED_AVAILABLE;
    117        }
    118        return internalIsLZMACompressionAvailable();
    119    }
    120
    121    /**
    122     * Checks if the signature matches what is expected for a .lzma file.
    123     *
    124     * @param   signature     the bytes to check
    125     * @param   length        the number of bytes to check
    126     * @return  true if signature matches the .lzma magic bytes, false otherwise
    127     */
    128    public static boolean matches(final byte[] signature, final int length) {
    129        if (length < HEADER_MAGIC.length) {
    130            return false;
    131        }
    132
    133        for (int i = 0; i < HEADER_MAGIC.length; ++i) {
    134            if (signature[i] != HEADER_MAGIC[i]) {
    135                return false;
    136            }
    137        }
    138
    139        return true;
    140    }
    141
    142    /**
    143     * Whether to cache the result of the LZMA check.
    144     *
    145     * <p>This defaults to {@code false} in an OSGi environment and {@code true} otherwise.</p>
    146     * @param doCache whether to cache the result
    147     */
    148    public static void setCacheLZMAAvailablity(final boolean doCache) {
    149        if (!doCache) {
    150            cachedLZMAAvailability = CachedAvailability.DONT_CACHE;
    151        } else if (cachedLZMAAvailability == CachedAvailability.DONT_CACHE) {
    152            final boolean hasLzma = internalIsLZMACompressionAvailable();
    153            cachedLZMAAvailability = hasLzma ? CachedAvailability.CACHED_AVAILABLE // NOSONAR
    154                : CachedAvailability.CACHED_UNAVAILABLE;
    155        }
    156    }
    157
    158    /** Private constructor to prevent instantiation of this utility class. */
    159    private LZMAUtils() {
    160    }
    161}