001: /*
002:
003: This software is OSI Certified Open Source Software.
004: OSI Certified is a certification mark of the Open Source Initiative.
005:
006: The license (Mozilla version 1.0) can be read at the MMBase site.
007: See http://www.MMBase.org/license
008:
009: */
010: package org.mmbase.util.transformers;
011:
012: import java.io.*;
013:
014: import org.mmbase.util.logging.*;
015:
016: /**
017: * A Filtering Writer based on CharTransformers.
018:
019: <pre>
020:
021: ____ _________
022: / \/ \
023: |this - PR --> W |
024: | PW | T |
025: \____/ \________/
026:
027:
028: PR: piped reader, this PW: this writer, T: transformer
029:
030: </pre>
031: * This writer can be instantiated with another Writer and a CharTransformer. All writing will be transformed by the given
032: * CharTransformer before arriving at the given Writer.
033: *
034: * When ready, this TransformingWriter should be 'closed'. A coding example can be found in this classe's main method.
035: *
036: * @author Michiel Meeuwissen
037: * @since MMBase-1.7
038: * @see ChainedCharTransformer
039: * @see TransformingReader
040: */
041:
042: public class TransformingWriter extends PipedWriter {
043:
044: private static final Logger log = Logging
045: .getLoggerInstance(TransformingWriter.class);
046:
047: private Writer out;
048: private CharTransformerLink link;
049:
050: public TransformingWriter(Writer out,
051: CharTransformer charTransformer) {
052: super ();
053: this .out = out;
054:
055: PipedReader r = new PipedReader();
056: try {
057: connect(r);
058: link = new CharTransformerLink(charTransformer, r, out,
059: false);
060: org.mmbase.util.ThreadPools.filterExecutor.execute(link);
061: } catch (IOException ioe) {
062: log.error(ioe.getMessage());
063: }
064: }
065:
066: /**
067: * {@inheritDoc}
068: * ALso closes the wrapped Writer.
069: */
070: public void close() throws IOException {
071: super .close(); // accept no more input
072: try {
073: while (!link.ready()) {
074: synchronized (link) { // make sure we have the lock
075: link.wait();
076: }
077: }
078: } catch (InterruptedException ie) {
079: log.warn("" + ie);
080: }
081: out.close();
082: }
083:
084: // main for testing purposes
085: public static void main(String[] args) {
086: Writer out = new OutputStreamWriter(System.out);
087: ChainedCharTransformer t = new ChainedCharTransformer();
088: t.add(new UpperCaser());
089: t.add(new SpaceReducer());
090: t.add(new Trimmer());
091: TransformingWriter writer = new TransformingWriter(out, t);
092: String testString = "use argument to change this string";
093: if (args.length > 0) {
094: testString = args[0];
095: }
096: try {
097: writer.write(testString);
098: writer.close();
099: } catch (Exception e) {
100: log.error("" + e + Logging.stackTrace(e));
101: }
102: }
103:
104: }
|