1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.store; |
7 | |
8 | import java.io.IOException; |
9 | import java.io.InputStream; |
10 | |
11 | import org.h2.message.DbException; |
12 | import org.h2.value.ValueLobDb; |
13 | |
14 | /** |
15 | * An input stream that reads from a remote LOB. |
16 | */ |
17 | class LobStorageRemoteInputStream extends InputStream { |
18 | |
19 | /** |
20 | * The data handler. |
21 | */ |
22 | private final DataHandler handler; |
23 | |
24 | /** |
25 | * The lob id. |
26 | */ |
27 | private final long lob; |
28 | |
29 | private final byte[] hmac; |
30 | |
31 | /** |
32 | * The position. |
33 | */ |
34 | private long pos; |
35 | |
36 | /** |
37 | * The remaining bytes in the lob. |
38 | */ |
39 | private long remainingBytes; |
40 | |
41 | public LobStorageRemoteInputStream(DataHandler handler, ValueLobDb lob, |
42 | byte[] hmac, long byteCount) { |
43 | this.handler = handler; |
44 | this.lob = lob.getLobId(); |
45 | this.hmac = hmac; |
46 | remainingBytes = byteCount; |
47 | } |
48 | |
49 | @Override |
50 | public int read() throws IOException { |
51 | byte[] buff = new byte[1]; |
52 | int len = read(buff, 0, 1); |
53 | return len < 0 ? len : (buff[0] & 255); |
54 | } |
55 | |
56 | @Override |
57 | public int read(byte[] buff) throws IOException { |
58 | return read(buff, 0, buff.length); |
59 | } |
60 | |
61 | @Override |
62 | public int read(byte[] buff, int off, int length) throws IOException { |
63 | if (length == 0) { |
64 | return 0; |
65 | } |
66 | length = (int) Math.min(length, remainingBytes); |
67 | if (length == 0) { |
68 | return -1; |
69 | } |
70 | try { |
71 | length = handler.readLob(lob, hmac, pos, buff, off, length); |
72 | } catch (DbException e) { |
73 | throw DbException.convertToIOException(e); |
74 | } |
75 | remainingBytes -= length; |
76 | if (length == 0) { |
77 | return -1; |
78 | } |
79 | pos += length; |
80 | return length; |
81 | } |
82 | |
83 | @Override |
84 | public long skip(long n) { |
85 | remainingBytes -= n; |
86 | pos += n; |
87 | return n; |
88 | } |
89 | |
90 | } |