01: /*
02:
03: This software is OSI Certified Open Source Software.
04: OSI Certified is a certification mark of the Open Source Initiative.
05:
06: The license (Mozilla version 1.0) can be read at the MMBase site.
07: See http://www.MMBase.org/license
08:
09: */
10: package org.mmbase.util.transformers;
11:
12: import java.io.*;
13: import org.mmbase.util.logging.*;
14:
15: /**
16: * You need only to implement transform(byte[]) you have the simplest
17: * kind of transformer (which is not 'streamable'). The name becoming your class name.
18: *
19: * @author Michiel Meeuwissen
20: * @since MMBase-1.7
21: */
22:
23: public abstract class ByteArrayToCharTransformer implements
24: ByteToCharTransformer {
25: private static Logger log = Logging
26: .getLoggerInstance(ByteArrayToCharTransformer.class);
27:
28: // javadoc inherited
29: public abstract String transform(byte[] r);
30:
31: // javadoc inherited
32: public final OutputStream transformBack(Reader r) {
33: return transformBack(r, new ByteArrayOutputStream());
34: }
35:
36: // javadoc inherited
37: public final Writer transform(InputStream in) {
38: return transform(in, new StringWriter());
39: }
40:
41: // javadoc inherited
42: public byte[] transformBack(String r) {
43: throw new UnsupportedOperationException(
44: "transformBack is not supported for this transformer");
45: }
46:
47: /**
48: * An implementation for transform(Reader, Writer) based on transform(String).
49: * These functions can be used by extensions to implement transform and transformBack
50: */
51: public Writer transform(InputStream in, Writer w) {
52: try {
53: ByteArrayOutputStream sw = new ByteArrayOutputStream();
54: while (true) {
55: int c = in.read();
56: if (c <= -1)
57: break;
58: sw.write(c);
59: }
60: String result = transform(sw.toByteArray());
61: w.write(result);
62: } catch (java.io.IOException e) {
63: log.error(e.toString(), e);
64: }
65: return w;
66: }
67:
68: public OutputStream transformBack(Reader in, OutputStream out) {
69: try {
70: StringWriter sw = new StringWriter();
71: while (true) {
72: int c = in.read();
73: if (c == -1)
74: break;
75: sw.write(c);
76: }
77: out.write(transformBack(sw.toString()));
78: } catch (java.io.IOException e) {
79: log.error(e.toString(), e);
80: }
81: return out;
82: }
83: }
|