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