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 the given input and output file names.
062     *
063     * @param inputFile TODO
064     * @param outputFile TODO
065     * @throws FileNotFoundException if the input file does not exist
066     * @throws FileNotFoundException TODO
067     * @throws IOException TODO
068     */
069    public Archive(final String inputFile, final String outputFile) throws FileNotFoundException, IOException {
070        this.inputFileName = inputFile;
071        this.outputFileName = outputFile;
072        inputStream = new FileInputStream(inputFile);
073        outputStream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));
074    }
075
076    /**
077     * Creates an Archive with streams for the input and output files. Note: If you use this method then calling
078     * {@link #setRemovePackFile(boolean)} will have no effect.
079     *
080     * @param inputStream TODO
081     * @param outputStream TODO
082     */
083    public Archive(final InputStream inputStream, final JarOutputStream outputStream) {
084        this.inputStream = inputStream;
085        this.outputStream = outputStream;
086    }
087
088    /**
089     * Unpacks the Archive from the input file to the output file
090     *
091     * @throws Pack200Exception TODO
092     * @throws IOException TODO
093     */
094    public void unpack() throws Pack200Exception, IOException {
095        outputStream.setComment("PACK200");
096        try {
097            if (!inputStream.markSupported()) {
098                inputStream = new BufferedInputStream(inputStream);
099                if (!inputStream.markSupported()) {
100                    throw new IllegalStateException();
101                }
102            }
103            inputStream.mark(2);
104            if (((inputStream.read() & 0xFF) | (inputStream.read() & 0xFF) << 8) == GZIPInputStream.GZIP_MAGIC) {
105                inputStream.reset();
106                inputStream = new BufferedInputStream(new GZIPInputStream(inputStream));
107            } else {
108                inputStream.reset();
109            }
110            inputStream.mark(4);
111            final int[] magic = {0xCA, 0xFE, 0xD0, 0x0D}; // Magic word for
112            // pack200
113            final int[] word = new int[4];
114            for (int i = 0; i < word.length; i++) {
115                word[i] = inputStream.read();
116            }
117            boolean compressedWithE0 = false;
118            for (int m = 0; m < magic.length; m++) {
119                if (word[m] != magic[m]) {
120                    compressedWithE0 = true;
121                }
122            }
123            inputStream.reset();
124            if (compressedWithE0) { // The original Jar was not packed, so just
125                // copy it across
126                final JarInputStream jarInputStream = new JarInputStream(inputStream);
127                JarEntry jarEntry;
128                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
129                    outputStream.putNextEntry(jarEntry);
130                    final byte[] bytes = new byte[16384];
131                    int bytesRead = jarInputStream.read(bytes);
132                    while (bytesRead != -1) {
133                        outputStream.write(bytes, 0, bytesRead);
134                        bytesRead = jarInputStream.read(bytes);
135                    }
136                    outputStream.closeEntry();
137                }
138            } else {
139                int i = 0;
140                while (available(inputStream)) {
141                    i++;
142                    final Segment segment = new Segment();
143                    segment.setLogLevel(logLevel);
144                    segment.setLogStream(logFile != null ? (OutputStream) logFile : (OutputStream) System.out);
145                    segment.setPreRead(false);
146
147                    if (i == 1) {
148                        segment.log(Segment.LOG_LEVEL_VERBOSE,
149                            "Unpacking from " + inputFileName + " to " + outputFileName);
150                    }
151                    segment.log(Segment.LOG_LEVEL_VERBOSE, "Reading segment " + i);
152                    if (overrideDeflateHint) {
153                        segment.overrideDeflateHint(deflateHint);
154                    }
155                    segment.unpack(inputStream, outputStream);
156                    outputStream.flush();
157
158                    if (inputStream instanceof FileInputStream) {
159                        inputFileName = ((FileInputStream) inputStream).getFD().toString();
160                    }
161                }
162            }
163        } finally {
164            try {
165                inputStream.close();
166            } catch (final Exception e) {
167            }
168            try {
169                outputStream.close();
170            } catch (final Exception e) {
171            }
172            if (logFile != null) {
173                try {
174                    logFile.close();
175                } catch (final Exception e) {
176                }
177            }
178        }
179        if (removePackFile) {
180            boolean deleted = false;
181            if (inputFileName != null) {
182                final File file = new File(inputFileName);
183                deleted = file.delete();
184            }
185            if (!deleted) {
186                throw new Pack200Exception("Failed to delete the input file.");
187            }
188        }
189    }
190
191    private boolean available(final InputStream inputStream) throws IOException {
192        inputStream.mark(1);
193        final int check = inputStream.read();
194        inputStream.reset();
195        return check != -1;
196    }
197
198    /**
199     * If removePackFile is set to true, the input file is deleted after unpacking.
200     *
201     * @param removePackFile If true, the input file is deleted after unpacking.
202     */
203    public void setRemovePackFile(final boolean removePackFile) {
204        this.removePackFile = removePackFile;
205    }
206
207    public void setVerbose(final boolean verbose) {
208        if (verbose) {
209            logLevel = Segment.LOG_LEVEL_VERBOSE;
210        } else if (logLevel == Segment.LOG_LEVEL_VERBOSE) {
211            logLevel = Segment.LOG_LEVEL_STANDARD;
212        }
213    }
214
215    public void setQuiet(final boolean quiet) {
216        if (quiet) {
217            logLevel = Segment.LOG_LEVEL_QUIET;
218        } else if (logLevel == Segment.LOG_LEVEL_QUIET) {
219            logLevel = Segment.LOG_LEVEL_QUIET;
220        }
221    }
222
223    public void setLogFile(final String logFileName) throws FileNotFoundException {
224        this.logFile = new FileOutputStream(logFileName);
225    }
226
227    public void setLogFile(final String logFileName, final boolean append) throws FileNotFoundException {
228        logFile = new FileOutputStream(logFileName, append);
229    }
230
231    public void setDeflateHint(final boolean deflateHint) {
232        overrideDeflateHint = true;
233        this.deflateHint = deflateHint;
234    }
235
236}