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 *
030 * @ThreadSafe
031 * @since 1.10
032 */
033public class LZMAUtils {
034
035    enum CachedAvailability {
036        DONT_CACHE, CACHED_AVAILABLE, CACHED_UNAVAILABLE
037    }
038
039    private static final FileNameUtil fileNameUtil;
040
041    /**
042     * LZMA Header Magic Bytes begin a LZMA file.
043     */
044    private static final byte[] HEADER_MAGIC = {
045        (byte) 0x5D, 0, 0
046    };
047
048    private static volatile CachedAvailability cachedLZMAAvailability;
049
050    static {
051        final Map<String, String> uncompressSuffix = new HashMap<>();
052        uncompressSuffix.put(".lzma", "");
053        uncompressSuffix.put("-lzma", "");
054        fileNameUtil = new FileNameUtil(uncompressSuffix, ".lzma");
055        cachedLZMAAvailability = CachedAvailability.DONT_CACHE;
056        setCacheLZMAAvailablity(!OsgiUtils.isRunningInOsgiEnvironment());
057    }
058
059    // only exists to support unit tests
060    static CachedAvailability getCachedLZMAAvailability() {
061        return cachedLZMAAvailability;
062    }
063
064    /**
065     * Maps the given file name to the name that the file should have after
066     * compression with LZMA.
067     *
068     * @param fileName name of a file
069     * @return name of the corresponding compressed file
070     * @deprecated Use {@link #getCompressedFileName(String)}.
071     */
072    @Deprecated
073    public static String getCompressedFilename(final String fileName) {
074        return fileNameUtil.getCompressedFileName(fileName);
075    }
076
077    /**
078     * Maps the given file name to the name that the file should have after
079     * compression with LZMA.
080     *
081     * @param fileName name of a file
082     * @return name of the corresponding compressed file
083     * @since 1.25.0
084     */
085    public static String getCompressedFileName(final String fileName) {
086        return fileNameUtil.getCompressedFileName(fileName);
087    }
088
089    /**
090     * Maps the given name of a LZMA-compressed file to the name that
091     * the file should have after uncompression.  Any file names with
092     * the generic ".lzma" suffix (or any other generic LZMA suffix)
093     * is mapped to a name without that suffix. If no LZMA suffix is
094     * detected, then the file name is returned unmapped.
095     *
096     * @param fileName name of a file
097     * @return name of the corresponding uncompressed file
098     * @deprecated Use {@link #getUncompressedFileName(String)}.
099     */
100    @Deprecated
101    public static String getUncompressedFilename(final String fileName) {
102        return fileNameUtil.getUncompressedFileName(fileName);
103    }
104
105    /**
106     * Maps the given name of a LZMA-compressed file to the name that
107     * the file should have after uncompression.  Any file names with
108     * the generic ".lzma" suffix (or any other generic LZMA suffix)
109     * is mapped to a name without that suffix. If no LZMA suffix is
110     * detected, then the file name is returned unmapped.
111     *
112     * @param fileName name of a file
113     * @return name of the corresponding uncompressed file
114     * @since 1.25.0
115     */
116    public static String getUncompressedFileName(final String fileName) {
117        return fileNameUtil.getUncompressedFileName(fileName);
118    }
119
120    private static boolean internalIsLZMACompressionAvailable() {
121        try {
122            LZMACompressorInputStream.matches(null, 0);
123            return true;
124        } catch (final NoClassDefFoundError error) { // NOSONAR
125            return false;
126        }
127    }
128
129    /**
130     * Detects common LZMA suffixes in the given file name.
131     *
132     * @param fileName name of a file
133     * @return {@code true} if the file name has a common LZMA suffix,
134     *         {@code false} otherwise
135     * @deprecated Use {@link #isCompressedFileName(String)}.
136     */
137    @Deprecated
138    public static boolean isCompressedFilename(final String fileName) {
139        return fileNameUtil.isCompressedFileName(fileName);
140    }
141
142    /**
143     * Detects common LZMA suffixes in the given file name.
144     *
145     * @param fileName name of a file
146     * @return {@code true} if the file name has a common LZMA suffix,
147     *         {@code false} otherwise
148     * @since 1.25.0
149     */
150    public static boolean isCompressedFileName(final String fileName) {
151        return fileNameUtil.isCompressedFileName(fileName);
152    }
153
154    /**
155     * Are the classes required to support LZMA compression available?
156     * @return true if the classes required to support LZMA
157     * compression are available
158     */
159    public static boolean isLZMACompressionAvailable() {
160        final CachedAvailability cachedResult = cachedLZMAAvailability;
161        if (cachedResult != CachedAvailability.DONT_CACHE) {
162            return cachedResult == CachedAvailability.CACHED_AVAILABLE;
163        }
164        return internalIsLZMACompressionAvailable();
165    }
166
167    /**
168     * Checks if the signature matches what is expected for a .lzma file.
169     *
170     * @param   signature     the bytes to check
171     * @param   length        the number of bytes to check
172     * @return  true if signature matches the .lzma magic bytes, false otherwise
173     */
174    public static boolean matches(final byte[] signature, final int length) {
175        if (length < HEADER_MAGIC.length) {
176            return false;
177        }
178
179        for (int i = 0; i < HEADER_MAGIC.length; ++i) {
180            if (signature[i] != HEADER_MAGIC[i]) {
181                return false;
182            }
183        }
184
185        return true;
186    }
187
188    /**
189     * Whether to cache the result of the LZMA check.
190     *
191     * <p>This defaults to {@code false} in an OSGi environment and {@code true} otherwise.</p>
192     * @param doCache whether to cache the result
193     */
194    public static void setCacheLZMAAvailablity(final boolean doCache) {
195        if (!doCache) {
196            cachedLZMAAvailability = CachedAvailability.DONT_CACHE;
197        } else if (cachedLZMAAvailability == CachedAvailability.DONT_CACHE) {
198            final boolean hasLzma = internalIsLZMACompressionAvailable();
199            cachedLZMAAvailability = hasLzma ? CachedAvailability.CACHED_AVAILABLE // NOSONAR
200                : CachedAvailability.CACHED_UNAVAILABLE;
201        }
202    }
203
204    /** Private constructor to prevent instantiation of this utility class. */
205    private LZMAUtils() {
206    }
207}