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.Reader;
13: import java.io.Writer;
14:
15: import org.mmbase.util.logging.*;
16:
17: /**
18: * Trims leading and trailing white space.
19: *
20: * @author Michiel Meeuwissen
21: * @since MMBase-1.7
22: * @version $Id: Trimmer.java,v 1.3 2007/08/04 08:09:14 michiel Exp $
23: */
24:
25: public class Trimmer extends ReaderTransformer implements
26: CharTransformer {
27: private static final Logger log = Logging
28: .getLoggerInstance(Trimmer.class);
29:
30: public String transform(String s) {
31: return s.trim();
32: }
33:
34: public Writer transform(Reader r, Writer w) {
35: StringBuilder word = new StringBuilder(); // current word
36: StringBuilder space = new StringBuilder();
37: try {
38: log.trace("Starting trim");
39: int c = r.read();
40:
41: while (c != -1 && Character.isWhitespace((char) c)) {
42: c = r.read();
43: }
44: boolean inWord = true;
45: while (true) {
46: if (Character.isWhitespace((char) c)) {
47: if (inWord) {
48: w.write(word.toString());
49: word.setLength(0);
50: inWord = false;
51: }
52: space.append((char) c);
53: } else {
54: if (!inWord) {
55: w.write(space.toString());
56: space.setLength(0);
57: inWord = true;
58: }
59: word.append((char) c);
60: }
61: c = r.read();
62: if (c == -1)
63: break;
64: }
65: // write last word, but not last spaces
66: if (inWord) {
67: w.write(word.toString());
68: }
69: } catch (java.io.IOException e) {
70: log.error(e.toString());
71: }
72: return w;
73: }
74:
75: public String toString() {
76: return "TRIMMER";
77: }
78: }
|