|
1 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 package org.mozilla.gecko.mozglue; |
|
7 |
|
8 import org.mozilla.gecko.mozglue.generatorannotations.WrapElementForJNI; |
|
9 |
|
10 import java.io.InputStream; |
|
11 import java.nio.ByteBuffer; |
|
12 import java.util.zip.Inflater; |
|
13 import java.util.zip.InflaterInputStream; |
|
14 |
|
15 public class NativeZip implements NativeReference { |
|
16 private static final int DEFLATE = 8; |
|
17 private static final int STORE = 0; |
|
18 |
|
19 private volatile long mObj; |
|
20 private InputStream mInput; |
|
21 |
|
22 public NativeZip(String path) { |
|
23 mObj = getZip(path); |
|
24 mInput = null; |
|
25 } |
|
26 |
|
27 public NativeZip(InputStream input) { |
|
28 if (!(input instanceof ByteBufferInputStream)) { |
|
29 throw new IllegalArgumentException("Got " + input.getClass() |
|
30 + ", but expected ByteBufferInputStream!"); |
|
31 } |
|
32 ByteBufferInputStream bbinput = (ByteBufferInputStream)input; |
|
33 mObj = getZipFromByteBuffer(bbinput.mBuf); |
|
34 mInput = input; |
|
35 } |
|
36 |
|
37 @Override |
|
38 public void finalize() { |
|
39 release(); |
|
40 } |
|
41 |
|
42 public void close() { |
|
43 release(); |
|
44 } |
|
45 |
|
46 @Override |
|
47 public void release() { |
|
48 if (mObj != 0) { |
|
49 _release(mObj); |
|
50 mObj = 0; |
|
51 } |
|
52 mInput = null; |
|
53 } |
|
54 |
|
55 @Override |
|
56 public boolean isReleased() { |
|
57 return (mObj == 0); |
|
58 } |
|
59 |
|
60 public InputStream getInputStream(String path) { |
|
61 if (isReleased()) { |
|
62 throw new IllegalStateException("Can't get path \"" + path |
|
63 + "\" because NativeZip is closed!"); |
|
64 } |
|
65 return _getInputStream(mObj, path); |
|
66 } |
|
67 |
|
68 private static native long getZip(String path); |
|
69 private static native long getZipFromByteBuffer(ByteBuffer buffer); |
|
70 private static native void _release(long obj); |
|
71 private native InputStream _getInputStream(long obj, String path); |
|
72 |
|
73 @WrapElementForJNI |
|
74 private InputStream createInputStream(ByteBuffer buffer, int compression) { |
|
75 if (compression != STORE && compression != DEFLATE) { |
|
76 throw new IllegalArgumentException("Unexpected compression: " + compression); |
|
77 } |
|
78 |
|
79 InputStream input = new ByteBufferInputStream(buffer, this); |
|
80 if (compression == DEFLATE) { |
|
81 Inflater inflater = new Inflater(true); |
|
82 input = new InflaterInputStream(input, inflater); |
|
83 } |
|
84 |
|
85 return input; |
|
86 } |
|
87 } |