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.functions.*;
14:
15: import org.mmbase.util.logging.*;
16:
17: /**
18: * Word wrapping as a transformer factory. Can be used in taglib e.g. like escape="wrap(20)"
19: *
20: * @author Michiel Meeuwissen
21: * @since MMBase-1.8
22: * @version $Id: WordWrapperFactory.java,v 1.5 2007/08/04 07:45:52 michiel Exp $
23: */
24:
25: public class WordWrapperFactory implements
26: ParameterizedTransformerFactory<CharTransformer> {
27: private static final Logger log = Logging
28: .getLoggerInstance(WordWrapperFactory.class);
29:
30: protected static final Parameter<Integer> LENGTH = new Parameter<Integer>(
31: "length", Integer.class, 80);
32: protected static final Parameter[] PARAMS = new Parameter[] { LENGTH };
33:
34: public Parameters createParameters() {
35: return new Parameters(PARAMS);
36: }
37:
38: /**
39: * Creates a parameterized transformer.
40: */
41: public CharTransformer createTransformer(final Parameters parameters) {
42: if (log.isDebugEnabled()) {
43: log.debug("Creating transformer, with " + parameters);
44: }
45: final int length = parameters.get(LENGTH);
46: return new ReaderTransformer() {
47:
48: public Writer transform(Reader r, Writer w) {
49: StringBuilder word = new StringBuilder(); // current word
50: try {
51: log.trace("Starting wrapping words.");
52: int ll = 0; // 'line lenght'
53: while (true) {
54: int c = r.read();
55: if (c == -1)
56: break;
57: if (Character.isWhitespace((char) c)) {
58: if (ll + word.length() > length) {
59: w.write('\n');
60: w.write(word.toString());
61: ll = 0;
62: word.length();
63: } else {
64: w.write(word.toString());
65: }
66: if (c == '\n') {
67: ll = 0;
68: w.write(c);
69: } else {
70: ll += word.length();
71: if (ll < length) {
72: w.write(c);
73: }
74: ll++;
75: }
76: word.setLength(0);
77: } else {
78: word.append((char) c);
79: }
80: }
81: // write last word
82: if (ll + word.length() > length) {
83: w.write('\n');
84: }
85: w.write(word.toString());
86: log.debug("Finished wrapping");
87: } catch (java.io.IOException e) {
88: log.error(e.toString());
89: }
90: return w;
91: };
92: };
93:
94: }
95:
96: }
|