1 15 package org.apache.tapestry.util.text; 16 17 25 public class MarkupCharacterTranslator implements ICharacterTranslator 26 { 27 private static final String SAFE_CHARACTERS = 28 "01234567890" 29 + "abcdefghijklmnopqrstuvwxyz" 30 + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 31 + "\t\n\r !#$%'()*+,-./:;=?@[\\]^_`{|}~"; 32 33 private static final String [][] ENTITIES = { 34 { "\"", """ }, 35 { "<", "<" }, 36 { ">", ">" }, 37 { "&", "&" } 38 }; 39 40 private static final ICharacterMatcher SAFE_MATCHER = new AsciiCharacterMatcher(SAFE_CHARACTERS); 41 private static final ICharacterTranslator ENTITY_TRANSLATOR = new AsciiCharacterTranslator(ENTITIES); 42 43 private boolean _encodeNonAscii; 44 private ICharacterMatcher _safeMatcher; 45 private ICharacterTranslator _entityTranslator; 46 47 public MarkupCharacterTranslator() 48 { 49 this(true); 50 } 51 52 public MarkupCharacterTranslator(boolean encodeNonAscii) 53 { 54 this(encodeNonAscii, SAFE_MATCHER, ENTITY_TRANSLATOR); 55 } 56 57 public MarkupCharacterTranslator(boolean encodeNonAscii, ICharacterMatcher safeMatcher, ICharacterTranslator entityTranslator) 58 { 59 _encodeNonAscii = encodeNonAscii; 60 _safeMatcher = safeMatcher; 61 _entityTranslator = entityTranslator; 62 } 63 64 public MarkupCharacterTranslator(boolean encodeNonAscii, String safeCharacters, String [][] entities) 65 { 66 _encodeNonAscii = encodeNonAscii; 67 _safeMatcher = new AsciiCharacterMatcher(safeCharacters); 68 _entityTranslator = new AsciiCharacterTranslator(entities); 69 } 70 71 74 public String translate(char ch) { 75 if (ch >= 128 && !_encodeNonAscii) 76 return null; 77 78 if (_safeMatcher.matches(ch)) 79 return null; 80 81 String entity = _entityTranslator.translate(ch); 82 if (entity != null) 83 return entity; 84 85 return "&#" + (int) ch + ";"; 88 } 89 } 90 | Popular Tags |