01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: /* $Id: ASCIIHexOutputStream.java 426584 2006-07-28 16:01:47Z jeremias $ */
19:
20: package org.apache.xmlgraphics.util.io;
21:
22: import java.io.OutputStream;
23: import java.io.FilterOutputStream;
24: import java.io.IOException;
25:
26: /**
27: * This class applies a ASCII Hex encoding to the stream.
28: *
29: * @version $Id: ASCIIHexOutputStream.java 426584 2006-07-28 16:01:47Z jeremias $
30: */
31: public class ASCIIHexOutputStream extends FilterOutputStream implements
32: Finalizable {
33:
34: private static final int EOL = 0x0A; //"\n"
35: private static final int EOD = 0x3E; //">"
36: private static final int ZERO = 0x30; //"0"
37: private static final int NINE = 0x39; //"9"
38: private static final int A = 0x41; //"A"
39: private static final int ADIFF = A - NINE - 1;
40:
41: private int posinline = 0;
42:
43: /** @see java.io.FilterOutputStream **/
44: public ASCIIHexOutputStream(OutputStream out) {
45: super (out);
46: }
47:
48: /** @see java.io.FilterOutputStream **/
49: public void write(int b) throws IOException {
50: b &= 0xFF;
51:
52: int digit1 = ((b & 0xF0) >> 4) + ZERO;
53: if (digit1 > NINE) {
54: digit1 += ADIFF;
55: }
56: out.write(digit1);
57:
58: int digit2 = (b & 0x0F) + ZERO;
59: if (digit2 > NINE) {
60: digit2 += ADIFF;
61: }
62: out.write(digit2);
63:
64: posinline++;
65: checkLineWrap();
66: }
67:
68: private void checkLineWrap() throws IOException {
69: //Maximum line length is 80 characters
70: if (posinline >= 40) {
71: out.write(EOL);
72: posinline = 0;
73: }
74: }
75:
76: /** @see Finalizable **/
77: public void finalizeStream() throws IOException {
78: checkLineWrap();
79: //Write closing character ">"
80: super .write(EOD);
81:
82: flush();
83: if (out instanceof Finalizable) {
84: ((Finalizable) out).finalizeStream();
85: }
86: }
87:
88: /** @see java.io.FilterOutputStream **/
89: public void close() throws IOException {
90: finalizeStream();
91: super.close();
92: }
93:
94: }
|