001: /*
002:
003: Derby - Class org.apache.derby.impl.jdbc.ReaderToAscii
004:
005: Licensed to the Apache Software Foundation (ASF) under one or more
006: contributor license agreements. See the NOTICE file distributed with
007: this work for additional information regarding copyright ownership.
008: The ASF licenses this file to you under the Apache License, Version 2.0
009: (the "License"); you may not use this file except in compliance with
010: the License. You may obtain a copy of the License at
011:
012: http://www.apache.org/licenses/LICENSE-2.0
013:
014: Unless required by applicable law or agreed to in writing, software
015: distributed under the License is distributed on an "AS IS" BASIS,
016: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017: See the License for the specific language governing permissions and
018: limitations under the License.
019:
020: */
021:
022: package org.apache.derby.impl.jdbc;
023:
024: import java.io.InputStream;
025: import java.io.Reader;
026: import java.io.IOException;
027: import java.sql.SQLException;
028:
029: /**
030: ReaderToAscii converts Reader (with characters) to a stream of ASCII characters.
031: */
032: public final class ReaderToAscii extends InputStream {
033:
034: private final Reader data;
035: private char[] conv;
036: private boolean closed;
037:
038: public ReaderToAscii(Reader data) {
039: this .data = data;
040: if (!(data instanceof UTF8Reader))
041: conv = new char[256];
042: }
043:
044: public int read() throws IOException {
045: if (closed)
046: throw new IOException();
047:
048: int c = data.read();
049: if (c == -1)
050: return -1;
051:
052: if (c <= 255)
053: return c & 0xFF;
054: else
055: return '?'; // Question mark - out of range character.
056: }
057:
058: public int read(byte[] buf, int off, int len) throws IOException {
059: if (closed)
060: throw new IOException();
061:
062: if (data instanceof UTF8Reader) {
063:
064: return ((UTF8Reader) data).readAsciiInto(buf, off, len);
065: }
066:
067: if (len > conv.length)
068: len = conv.length;
069:
070: len = data.read(conv, 0, len);
071: if (len == -1)
072: return -1;
073:
074: for (int i = 0; i < len; i++) {
075: char c = conv[i];
076:
077: byte cb;
078: if (c <= 255)
079: cb = (byte) c;
080: else
081: cb = (byte) '?'; // Question mark - out of range character.
082:
083: buf[off++] = cb;
084: }
085:
086: return len;
087: }
088:
089: public long skip(long len) throws IOException {
090: if (closed)
091: throw new IOException();
092:
093: return data.skip(len);
094: }
095:
096: public void close() throws IOException {
097: if (!closed) {
098: closed = true;
099: data.close();
100: }
101: }
102: }
|