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