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 org.mmbase.util.functions.*;
13: import java.io.Reader;
14: import java.io.Writer;
15:
16: /**
17: * Factories {@link CharTransformer}'s which mirror the input, but only between 'from' and 'to'
18: * parameters. So, those transformers work like {@link java.lang.String#substring}.
19: * And as a bonus you can specify the parameter 'ellipsis' (the three dots at the end of the text)
20: * to use when a text has been 'substringed'...
21: *
22: * @author Michiel Meeuwissen
23: * @author André van Toly
24: * @since MMBase-1.8
25: * @version $Id: SubstringFactory.java,v 1.9 2007/08/04 07:45:52 michiel Exp $
26: */
27:
28: public class SubstringFactory implements
29: ParameterizedTransformerFactory<CharTransformer> {
30:
31: protected final static Parameter<Integer> FROM = new Parameter<Integer>(
32: "from", Integer.class, 0);
33: protected final static Parameter<Integer> TO = new Parameter<Integer>(
34: "to", Integer.class, Integer.MAX_VALUE);
35: protected final static Parameter<String> ELLIPSIS = new Parameter<String>(
36: "ellipsis", String.class, "");
37: protected final static Parameter[] PARAMS = { FROM, TO, ELLIPSIS };
38:
39: public CharTransformer createTransformer(Parameters parameters) {
40: return new Substring(parameters.get(FROM), parameters.get(TO),
41: parameters.get(ELLIPSIS));
42: }
43:
44: public Parameters createParameters() {
45: return new Parameters(PARAMS);
46: }
47:
48: protected class Substring extends ReaderTransformer {
49:
50: private final int from;
51: private final int to;
52: private final String ellipsis;
53:
54: Substring(int f, int t, String e) {
55: from = f;
56: to = t;
57: ellipsis = e;
58: }
59:
60: // implementation, javadoc inherited
61: public Writer transform(Reader r, Writer w) {
62: if (from < 0 || to < 0)
63: throw new UnsupportedOperationException(
64: "When using streams, it is not possible to use negative values.");
65: int current = 0;
66: try {
67: while (true) {
68: int c = r.read();
69: if (c == -1)
70: break;
71: if (current >= from) {
72: w.write(c);
73: }
74: current++;
75: if (current >= to) {
76: if (ellipsis != null && (!ellipsis.equals("")))
77: w.write(ellipsis);
78: break;
79: }
80: }
81: } catch (java.io.IOException e) {
82: throw new RuntimeException(e);
83: }
84: return w;
85: }
86:
87: public String toString() {
88: return "SUBSTRING(" + from + "," + to + "," + ellipsis
89: + ")";
90: }
91: }
92:
93: }
|