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;
023import org.apache.commons.compress.compressors.FileNameUtil;
024
025/**
026 * Utility code for the lzma compression format.
027 * @ThreadSafe
028 * @since 1.10
029 */
030public class LZMAUtils {
031
032    private static final FileNameUtil fileNameUtil;
033
034    /**
035     * LZMA Header Magic Bytes begin a LZMA file.
036     */
037    private static final byte[] HEADER_MAGIC = {
038        (byte) 0x5D, 0, 0
039    };
040
041    static enum CachedAvailability {
042        DONT_CACHE, CACHED_AVAILABLE, CACHED_UNAVAILABLE
043    }
044
045    private static volatile CachedAvailability cachedLZMAAvailability;
046
047    static {
048        Map<String, String> uncompressSuffix = new HashMap<String, String>();
049        uncompressSuffix.put(".lzma", "");
050        uncompressSuffix.put("-lzma", "");
051        fileNameUtil = new FileNameUtil(uncompressSuffix, ".lzma");
052        cachedLZMAAvailability = CachedAvailability.DONT_CACHE;
053        try {
054            Class.forName("org.osgi.framework.BundleEvent");
055        } catch (Exception ex) {
056            setCacheLZMAAvailablity(true);
057        }
058    }
059
060    /** Private constructor to prevent instantiation of this utility class. */
061    private LZMAUtils() {
062    }
063
064    /**
065     * Checks if the signature matches what is expected for a .lzma file.
066     *
067     * @param   signature     the bytes to check
068     * @param   length        the number of bytes to check
069     * @return  true if signature matches the .lzma magic bytes, false otherwise
070     */
071    public static boolean matches(byte[] signature, int length) {
072        if (length < HEADER_MAGIC.length) {
073            return false;
074        }
075
076        for (int i = 0; i < HEADER_MAGIC.length; ++i) {
077            if (signature[i] != HEADER_MAGIC[i]) {
078                return false;
079            }
080        }
081
082        return true;
083    }
084
085    /**
086     * Are the classes required to support LZMA compression available?
087     */
088    public static boolean isLZMACompressionAvailable() {
089        final CachedAvailability cachedResult = cachedLZMAAvailability;
090        if (cachedResult != CachedAvailability.DONT_CACHE) {
091            return cachedResult == CachedAvailability.CACHED_AVAILABLE;
092        }
093        return internalIsLZMACompressionAvailable();
094    }
095
096    private static boolean internalIsLZMACompressionAvailable() {
097        try {
098            LZMACompressorInputStream.matches(null, 0);
099            return true;
100        } catch (NoClassDefFoundError error) {
101            return false;
102        }
103    }
104
105    /**
106     * Detects common lzma suffixes in the given filename.
107     *
108     * @param filename name of a file
109     * @return {@code true} if the filename has a common lzma suffix,
110     *         {@code false} otherwise
111     */
112    public static boolean isCompressedFilename(String filename) {
113        return fileNameUtil.isCompressedFilename(filename);
114    }
115
116    /**
117     * Maps the given name of a lzma-compressed file to the name that
118     * the file should have after uncompression.  Any filenames with
119     * the generic ".lzma" suffix (or any other generic lzma suffix)
120     * is mapped to a name without that suffix. If no lzma suffix is
121     * detected, then the filename is returned unmapped.
122     *
123     * @param filename name of a file
124     * @return name of the corresponding uncompressed file
125     */
126    public static String getUncompressedFilename(String filename) {
127        return fileNameUtil.getUncompressedFilename(filename);
128    }
129
130    /**
131     * Maps the given filename to the name that the file should have after
132     * compression with lzma.
133     *
134     * @param filename name of a file
135     * @return name of the corresponding compressed file
136     */
137    public static String getCompressedFilename(String filename) {
138        return fileNameUtil.getCompressedFilename(filename);
139    }
140
141    /**
142     * Whether to cache the result of the LZMA check.
143     *
144     * <p>This defaults to {@code false} in an OSGi environment and {@code true} otherwise.</p>
145     * @param doCache whether to cache the result
146     */
147    public static void setCacheLZMAAvailablity(boolean doCache) {
148        if (!doCache) {
149            cachedLZMAAvailability = CachedAvailability.DONT_CACHE;
150        } else if (cachedLZMAAvailability == CachedAvailability.DONT_CACHE) {
151            final boolean hasLzma = internalIsLZMACompressionAvailable();
152            cachedLZMAAvailability = hasLzma ? CachedAvailability.CACHED_AVAILABLE
153                : CachedAvailability.CACHED_UNAVAILABLE;
154        }
155    }
156
157    // only exists to support unit tests
158    static CachedAvailability getCachedLZMAAvailability() {
159        return cachedLZMAAvailability;
160    }
161}