01: // Copyright (C) 1999-2001 by Jason Hunter <jhunter_AT_acm_DOT_org>.
02: // All rights reserved. Use of this class is limited.
03: // Please see the LICENSE for more information.
04:
05: package com.oreilly.servlet.multipart;
06:
07: import java.io.OutputStream;
08: import java.io.FilterOutputStream;
09: import java.io.IOException;
10:
11: /**
12: * A <code>MacBinaryDecoderOutput</code> filters MacBinary files to normal
13: * files on the fly; optimized for speed more than readability.
14: *
15: * @author Jason Hunter
16: */
17: public class MacBinaryDecoderOutputStream extends FilterOutputStream {
18: private int bytesFiltered = 0;
19: private int dataForkLength = 0;
20:
21: public MacBinaryDecoderOutputStream(OutputStream out) {
22: super (out);
23: }
24:
25: public void write(int b) throws IOException {
26: // Bytes 83 through 86 are a long representing the data fork length
27: // Check <= 86 first to short circuit early in the common case
28: if (bytesFiltered <= 86 && bytesFiltered >= 83) {
29: int leftShift = (86 - bytesFiltered) * 8;
30: dataForkLength = dataForkLength | (b & 0xff) << leftShift;
31: }
32:
33: // Bytes 128 up to (128 + dataForkLength - 1) are the data fork
34: else if (bytesFiltered < (128 + dataForkLength)
35: && bytesFiltered >= 128) {
36: out.write(b);
37: }
38:
39: bytesFiltered++;
40: }
41:
42: public void write(byte b[]) throws IOException {
43: write(b, 0, b.length);
44: }
45:
46: public void write(byte b[], int off, int len) throws IOException {
47: // If the write is for content past the end of the data fork, ignore
48: if (bytesFiltered >= (128 + dataForkLength)) {
49: bytesFiltered += len;
50: }
51: // If the write is entirely within the data fork, write it directly
52: else if (bytesFiltered >= 128
53: && (bytesFiltered + len) <= (128 + dataForkLength)) {
54: out.write(b, off, len);
55: bytesFiltered += len;
56: }
57: // Otherwise, do the write a byte at a time to get the logic above
58: else {
59: for (int i = 0; i < len; i++) {
60: write(b[off + i]);
61: }
62: }
63: }
64: }
|