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