1 | /* |
2 | |
3 | Derby - Class org.apache.derby.impl.jdbc.ReaderToAscii |
4 | |
5 | Copyright 2004 The Apache Software Foundation or its licensors, as applicable. |
6 | |
7 | Licensed under the Apache License, Version 2.0 (the "License"); |
8 | you may not use this file except in compliance with the License. |
9 | You may obtain a copy of the License at |
10 | |
11 | http://www.apache.org/licenses/LICENSE-2.0 |
12 | |
13 | Unless required by applicable law or agreed to in writing, software |
14 | distributed under the License is distributed on an "AS IS" BASIS, |
15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
16 | See the License for the specific language governing permissions and |
17 | limitations under the License. |
18 | |
19 | */ |
20 | |
21 | package org.apache.derby.impl.jdbc; |
22 | |
23 | import java.io.InputStream; |
24 | import java.io.Reader; |
25 | import java.io.IOException; |
26 | import java.sql.SQLException; |
27 | |
28 | /** |
29 | ReaderToAscii converts Reader (with characters) to a stream of ASCII characters. |
30 | */ |
31 | public final class ReaderToAscii extends InputStream |
32 | { |
33 | |
34 | private final Reader data; |
35 | private char[] conv; |
36 | private boolean closed; |
37 | |
38 | public ReaderToAscii(Reader data) |
39 | { |
40 | this.data = data; |
41 | if (!(data instanceof UTF8Reader)) |
42 | conv = new char[256]; |
43 | } |
44 | |
45 | public int read() throws IOException |
46 | { |
47 | if (closed) |
48 | throw new IOException(); |
49 | |
50 | int c = data.read(); |
51 | if (c == -1) |
52 | return -1; |
53 | |
54 | if (c <= 255) |
55 | return c & 0xFF; |
56 | else |
57 | return '?'; // Question mark - out of range character. |
58 | } |
59 | |
60 | public int read(byte[] buf, int off, int len) throws IOException |
61 | { |
62 | if (closed) |
63 | throw new IOException(); |
64 | |
65 | if (data instanceof UTF8Reader) { |
66 | |
67 | return ((UTF8Reader) data).readAsciiInto(buf, off, len); |
68 | } |
69 | |
70 | if (len > conv.length) |
71 | len = conv.length; |
72 | |
73 | len = data.read(conv, 0, len); |
74 | if (len == -1) |
75 | return -1; |
76 | |
77 | for (int i = 0; i < len; i++) { |
78 | char c = conv[i]; |
79 | |
80 | byte cb; |
81 | if (c <= 255) |
82 | cb = (byte) c; |
83 | else |
84 | cb = (byte) '?'; // Question mark - out of range character. |
85 | |
86 | buf[off++] = cb; |
87 | } |
88 | |
89 | return len; |
90 | } |
91 | |
92 | public long skip(long len) throws IOException { |
93 | if (closed) |
94 | throw new IOException(); |
95 | |
96 | return data.skip(len); |
97 | } |
98 | |
99 | public void close() throws IOException |
100 | { |
101 | if (!closed) { |
102 | closed = true; |
103 | data.close(); |
104 | } |
105 | } |
106 | } |