    001/*
    002 *  Licensed to the Apache Software Foundation (ASF) under one or more
    003 *  contributor license agreements.  See the NOTICE file distributed with
    004 *  this work for additional information regarding copyright ownership.
    005 *  The ASF licenses this file to You under the Apache License, Version 2.0
    006 *  (the "License"); you may not use this file except in compliance with
    007 *  the License.  You may obtain a copy of the License at
    008 *
    009 *     http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 *  Unless required by applicable law or agreed to in writing, software
    012 *  distributed under the License is distributed on an "AS IS" BASIS,
    013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 *  See the License for the specific language governing permissions and
    015 *  limitations under the License.
    016 */
    017package org.apache.commons.compress.harmony.unpack200;
    018
    019import java.io.BufferedInputStream;
    020import java.io.BufferedOutputStream;
    021import java.io.File;
    022import java.io.FileInputStream;
    023import java.io.FileNotFoundException;
    024import java.io.FileOutputStream;
    025import java.io.IOException;
    026import java.io.InputStream;
    027import java.io.OutputStream;
    028import java.util.jar.JarEntry;
    029import java.util.jar.JarInputStream;
    030import java.util.jar.JarOutputStream;
    031import java.util.zip.GZIPInputStream;
    032
    033import org.apache.commons.compress.harmony.pack200.Pack200Exception;
    034
    035/**
    036 * Archive is the main entry point to unpack200. An archive is constructed with either two file names, a pack file and
    037 * an output file name or an input stream and an output streams. Then {@code unpack()} is called, to unpack the
    038 * pack200 archive.
    039 */
    040public class Archive {
    041
    042    private InputStream inputStream;
    043
    044    private final JarOutputStream outputStream;
    045
    046    private boolean removePackFile;
    047
    048    private int logLevel = Segment.LOG_LEVEL_STANDARD;
    049
    050    private FileOutputStream logFile;
    051
    052    private boolean overrideDeflateHint;
    053
    054    private boolean deflateHint;
    055
    056    private String inputFileName;
    057
    058    private String outputFileName;
    059
    060    /**
    061     * Creates an Archive with streams for the input and output files. Note: If you use this method then calling
    062     * {@link #setRemovePackFile(boolean)} will have no effect.
    063     *
    064     * @param inputStream TODO
    065     * @param outputStream TODO
    066     */
    067    public Archive(final InputStream inputStream, final JarOutputStream outputStream) {
    068        this.inputStream = inputStream;
    069        this.outputStream = outputStream;
    070    }
    071
    072    /**
    073     * Creates an Archive with the given input and output file names.
    074     *
    075     * @param inputFile TODO
    076     * @param outputFile TODO
    077     * @throws FileNotFoundException if the input file does not exist
    078     * @throws FileNotFoundException TODO
    079     * @throws IOException TODO
    080     */
    081    public Archive(final String inputFile, final String outputFile) throws FileNotFoundException, IOException {
    082        this.inputFileName = inputFile;
    083        this.outputFileName = outputFile;
    084        inputStream = new FileInputStream(inputFile);
    085        outputStream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
    086    }
    087
    088    private boolean available(final InputStream inputStream) throws IOException {
    089        inputStream.mark(1);
    090        final int check = inputStream.read();
    091        inputStream.reset();
    092        return check != -1;
    093    }
    094
    095    public void setDeflateHint(final boolean deflateHint) {
    096        overrideDeflateHint = true;
    097        this.deflateHint = deflateHint;
    098    }
    099
    100    public void setLogFile(final String logFileName) throws FileNotFoundException {
    101        this.logFile = new FileOutputStream(logFileName);
    102    }
    103
    104    public void setLogFile(final String logFileName, final boolean append) throws FileNotFoundException {
    105        logFile = new FileOutputStream(logFileName, append);
    106    }
    107
    108    public void setQuiet(final boolean quiet) {
    109        if (quiet || logLevel == Segment.LOG_LEVEL_QUIET) {
    110            logLevel = Segment.LOG_LEVEL_QUIET;
    111        }
    112    }
    113
    114    /**
    115     * If removePackFile is set to true, the input file is deleted after unpacking.
    116     *
    117     * @param removePackFile If true, the input file is deleted after unpacking.
    118     */
    119    public void setRemovePackFile(final boolean removePackFile) {
    120        this.removePackFile = removePackFile;
    121    }
    122
    123    public void setVerbose(final boolean verbose) {
    124        if (verbose) {
    125            logLevel = Segment.LOG_LEVEL_VERBOSE;
    126        } else if (logLevel == Segment.LOG_LEVEL_VERBOSE) {
    127            logLevel = Segment.LOG_LEVEL_STANDARD;
    128        }
    129    }
    130
    131    /**
    132     * Unpacks the Archive from the input file to the output file
    133     *
    134     * @throws Pack200Exception TODO
    135     * @throws IOException TODO
    136     */
    137    public void unpack() throws Pack200Exception, IOException {
    138        outputStream.setComment("PACK200");
    139        try {
    140            if (!inputStream.markSupported()) {
    141                inputStream = new BufferedInputStream(inputStream);
    142                if (!inputStream.markSupported()) {
    143                    throw new IllegalStateException();
    144                }
    145            }
    146            inputStream.mark(2);
    147            if ((inputStream.read() & 0xFF | (inputStream.read() & 0xFF) << 8) == GZIPInputStream.GZIP_MAGIC) {
    148                inputStream.reset();
    149                inputStream = new BufferedInputStream(new GZIPInputStream(inputStream));
    150            } else {
    151                inputStream.reset();
    152            }
    153            inputStream.mark(4);
    154            final int[] magic = {0xCA, 0xFE, 0xD0, 0x0D}; // Magic word for
    155            // pack200
    156            final int[] word = new int[4];
    157            for (int i = 0; i < word.length; i++) {
    158                word[i] = inputStream.read();
    159            }
    160            boolean compressedWithE0 = false;
    161            for (int m = 0; m < magic.length; m++) {
    162                if (word[m] != magic[m]) {
    163                    compressedWithE0 = true;
    164                }
    165            }
    166            inputStream.reset();
    167            if (compressedWithE0) { // The original Jar was not packed, so just
    168                // copy it across
    169                final JarInputStream jarInputStream = new JarInputStream(inputStream);
    170                JarEntry jarEntry;
    171                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
    172                    outputStream.putNextEntry(jarEntry);
    173                    final byte[] bytes = new byte[16384];
    174                    int bytesRead = jarInputStream.read(bytes);
    175                    while (bytesRead != -1) {
    176                        outputStream.write(bytes, 0, bytesRead);
    177                        bytesRead = jarInputStream.read(bytes);
    178                    }
    179                    outputStream.closeEntry();
    180                }
    181            } else {
    182                int i = 0;
    183                while (available(inputStream)) {
    184                    i++;
    185                    final Segment segment = new Segment();
    186                    segment.setLogLevel(logLevel);
    187                    segment.setLogStream(logFile != null ? (OutputStream) logFile : (OutputStream) System.out);
    188                    segment.setPreRead(false);
    189
    190                    if (i == 1) {
    191                        segment.log(Segment.LOG_LEVEL_VERBOSE,
    192                            "Unpacking from " + inputFileName + " to " + outputFileName);
    193                    }
    194                    segment.log(Segment.LOG_LEVEL_VERBOSE, "Reading segment " + i);
    195                    if (overrideDeflateHint) {
    196                        segment.overrideDeflateHint(deflateHint);
    197                    }
    198                    segment.unpack(inputStream, outputStream);
    199                    outputStream.flush();
    200
    201                    if (inputStream instanceof FileInputStream) {
    202                        inputFileName = ((FileInputStream) inputStream).getFD().toString();
    203                    }
    204                }
    205            }
    206        } finally {
    207            try {
    208                inputStream.close();
    209            } catch (final Exception e) {
    210            }
    211            try {
    212                outputStream.close();
    213            } catch (final Exception e) {
    214            }
    215            if (logFile != null) {
    216                try {
    217                    logFile.close();
    218                } catch (final Exception e) {
    219                }
    220            }
    221        }
    222        if (removePackFile) {
    223            boolean deleted = false;
    224            if (inputFileName != null) {
    225                final File file = new File(inputFileName);
    226                deleted = file.delete();
    227            }
    228            if (!deleted) {
    229                throw new Pack200Exception("Failed to delete the input file.");
    230            }
    231        }
    232    }
    233
    234}