1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.betwixt.strategy;
17
18 import org.apache.commons.betwixt.XMLUtils;
19
20 /***
21 * <code>NameMapper</code> implementation that processes a name by replacing or stripping
22 * illegal characters before passing result down the chain.
23 *
24 * @author Robert Burrell Donkin
25 * @since 0.5
26 */
27 public class BadCharacterReplacingNMapper implements NameMapper {
28 /*** Next mapper in chain, possibly null */
29 private NameMapper chainedMapper;
30 /*** Replacement character, possibly null */
31 private Character replacement = null;
32
33 /***
34 * Constructs a replacing mapper which delegates to given mapper.
35 * @param chainedMapper next link in processing chain, possibly null
36 */
37 public BadCharacterReplacingNMapper(NameMapper chainedMapper) {
38 this.chainedMapper = chainedMapper;
39 }
40
41 /***
42 * Gets the character that should be used to replace bad characters
43 * if null then bad characters will be deleted.
44 * @return the replacement Character possibly null
45 */
46 public Character getReplacement() {
47 return replacement;
48 }
49
50 /***
51 * Sets the character that should be used to replace bad characters.
52 * @param replacement the Charcter to be used for replacement if not null.
53 * Otherwise, indicates that illegal characters should be deleted.
54 */
55 public void setReplacement( Character replacement ) {
56 this.replacement = replacement;
57 }
58
59 /***
60 * This implementation processes characters which are not allowed in xml
61 * element names and then returns the result from the next link in the chain.
62 * This processing consists of deleting them if no replacement character
63 * has been set.
64 * Otherwise, the character will be replaced.
65 *
66 * @param typeName the string to convert
67 * @return the processed input
68 */
69 public String mapTypeToElementName(String typeName) {
70
71 StringBuffer buffer = new StringBuffer( typeName );
72 for (int i=0, size = buffer.length(); i< size; i++) {
73 char nextChar = buffer.charAt( i );
74 boolean bad = false;
75 if ( i==0 ) {
76 bad = !XMLUtils.isNameStartChar( nextChar );
77 } else {
78 bad = !XMLUtils.isNameChar( nextChar );
79 }
80
81 if (bad) {
82 if ( replacement != null ) {
83 buffer.setCharAt( i, replacement.charValue() );
84 } else {
85
86 buffer.deleteCharAt( i );
87 i--;
88 size--;
89 }
90 }
91 }
92
93 if ( buffer.length() == 0 ) {
94 throw new IllegalArgumentException(
95 "Element name contains no legal characters and no replacements have been set.");
96 }
97
98 typeName = buffer.toString();
99
100 if ( chainedMapper == null ) {
101 return typeName;
102 }
103 return chainedMapper.mapTypeToElementName( typeName );
104 }
105 }