001/*
002 * Copyright 2007-2018 The jdeb developers.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.vafer.jdeb;
018
019import java.io.OutputStream;
020
021import org.apache.commons.compress.compressors.CompressorException;
022import org.apache.commons.compress.compressors.CompressorStreamFactory;
023
024/**
025 * Compression method used for the data file.
026 */
027public enum Compression {
028
029    NONE(""),
030    GZIP(".gz"),
031    BZIP2(".bz2"),
032    XZ(".xz");
033
034    private String extension;
035
036    private Compression(String extension) {
037        this.extension = extension;
038    }
039
040    /**
041     * Returns the extension of the compression method
042     */
043    public String getExtension() {
044        return extension;
045    }
046
047    public OutputStream toCompressedOutputStream(OutputStream out) throws CompressorException {
048        switch (this) {
049            case GZIP:
050                return new CompressorStreamFactory().createCompressorOutputStream("gz", out);
051            case BZIP2:
052                return new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
053            case XZ:
054                return new CompressorStreamFactory().createCompressorOutputStream("xz", out);
055            default:
056                return out;
057        }
058    }
059
060    /**
061     * Returns the compression method corresponding to the specified name.
062     * The matching is case insensitive.
063     *
064     * @param name the name of the compression method
065     * @return the compression method, or null if not recognized
066     */
067    public static Compression toEnum(String name) {
068        if ("gzip".equalsIgnoreCase(name) || "gz".equalsIgnoreCase(name)) {
069            return GZIP;
070        } else if ("bzip2".equalsIgnoreCase(name) || "bz2".equalsIgnoreCase(name)) {
071            return BZIP2;
072        } else if ("xz".equalsIgnoreCase(name)) {
073            return XZ;
074        } else if ("none".equalsIgnoreCase(name)) {
075            return NONE;
076        } else {
077            return null;
078        }
079    }
080}