01: /*
02: * This file is part of "SnipSnap Radeox Rendering Engine".
03: *
04: * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
05: * All Rights Reserved.
06: *
07: * Please visit http://radeox.org/ for updates and contact.
08: *
09: * --LICENSE NOTICE--
10: * Licensed under the Apache License, Version 2.0 (the "License");
11: * you may not use this file except in compliance with the License.
12: * You may obtain a copy of the License at
13: *
14: * http://www.apache.org/licenses/LICENSE-2.0
15: *
16: * Unless required by applicable law or agreed to in writing, software
17: * distributed under the License is distributed on an "AS IS" BASIS,
18: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19: * See the License for the specific language governing permissions and
20: * limitations under the License.
21: * --LICENSE NOTICE--
22: */
23: package org.radeox.macro;
24:
25: import java.util.HashMap;
26: import java.util.Map;
27: import java.util.StringTokenizer;
28:
29: import org.radeox.util.Encoder;
30:
31: /**
32: * A specialized macro that allows to preserve certain special characters by
33: * creating character entities. The subclassing macro may decide whether to call
34: * replace() before or after executing the actual macro substitution.
35: *
36: * @author Matthias L. Jugel
37: * @version $Id: Preserved.java 7756 2006-04-13 12:25:49Z ian@caret.cam.ac.uk $
38: */
39:
40: public abstract class Preserved extends BaseMacro {
41: private Map special = new HashMap();
42:
43: private String specialString = "";
44:
45: /**
46: * Encode special character c by replacing with it's hex character entity
47: * code.
48: */
49: protected void addSpecial(char c) {
50: addSpecial("" + c, Encoder.toEntity(c));
51: }
52:
53: /**
54: * Add a replacement for the special character c which may be a string
55: *
56: * @param c
57: * the character to replace
58: * @param replacement
59: * the new string
60: */
61: protected void addSpecial(String c, String replacement) {
62: specialString += c;
63: special.put(c, replacement);
64: }
65:
66: /**
67: * Actually replace specials in source. This method can be used by
68: * subclassing macros.
69: *
70: * @param source
71: * String to encode
72: * @return encoded Encoded string
73: */
74: protected String replace(String source) {
75: StringBuffer tmp = new StringBuffer();
76: StringTokenizer stringTokenizer = new StringTokenizer(source,
77: specialString, true);
78: while (stringTokenizer.hasMoreTokens()) {
79: String current = stringTokenizer.nextToken();
80: if (special.containsKey(current)) {
81: current = (String) special.get(current);
82: }
83: tmp.append(current);
84: }
85: return tmp.toString();
86: }
87: }
|