1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.commons.compress.compressors.lzma;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23
24 import org.apache.commons.compress.MemoryLimitException;
25 import org.apache.commons.compress.compressors.CompressorInputStream;
26 import org.apache.commons.compress.utils.InputStreamStatistics;
27 import org.apache.commons.io.input.BoundedInputStream;
28 import org.tukaani.xz.LZMAInputStream;
29
30
31
32
33
34
35 public class LZMACompressorInputStream extends CompressorInputStream implements InputStreamStatistics {
36
37
38
39
40
41
42
43
44
45
46 public static boolean matches(final byte[] signature, final int length) {
47 return signature != null && length >= 3 && signature[0] == 0x5d && signature[1] == 0 && signature[2] == 0;
48 }
49
50 private final BoundedInputStream countingStream;
51
52 private final InputStream in;
53
54
55
56
57
58
59
60
61
62 public LZMACompressorInputStream(final InputStream inputStream) throws IOException {
63 in = new LZMAInputStream(countingStream = BoundedInputStream.builder().setInputStream(inputStream).get(), -1);
64 }
65
66
67
68
69
70
71
72
73
74
75
76
77
78 public LZMACompressorInputStream(final InputStream inputStream, final int memoryLimitInKb) throws IOException {
79 try {
80 in = new LZMAInputStream(countingStream = BoundedInputStream.builder().setInputStream(inputStream).get(), memoryLimitInKb);
81 } catch (final org.tukaani.xz.MemoryLimitException e) {
82
83 throw new MemoryLimitException(e.getMemoryNeeded(), e.getMemoryLimit(), e);
84 }
85 }
86
87
88 @Override
89 public int available() throws IOException {
90 return in.available();
91 }
92
93
94 @Override
95 public void close() throws IOException {
96 in.close();
97 }
98
99
100
101
102 @Override
103 public long getCompressedCount() {
104 return countingStream.getCount();
105 }
106
107
108 @Override
109 public int read() throws IOException {
110 final int ret = in.read();
111 count(ret == -1 ? 0 : 1);
112 return ret;
113 }
114
115
116 @Override
117 public int read(final byte[] buf, final int off, final int len) throws IOException {
118 final int ret = in.read(buf, off, len);
119 count(ret);
120 return ret;
121 }
122
123
124 @Override
125 public long skip(final long n) throws IOException {
126 return org.apache.commons.io.IOUtils.skip(in, n);
127 }
128 }