1 19 20 package org.netbeans.modules.lexer.gen.util; 21 22 28 29 class LexerGenUtilitiesImpl { 30 31 private static final char[] HEX_DIGIT = {'0','1','2','3','4','5','6','7', 32 '8','9','A','B','C','D','E','F'}; 33 34 35 38 public static String fromSource(String s) { 39 StringBuffer sb = new StringBuffer (); 40 41 int len = s.length(); 42 for (int i = 0; i < len; i++) { 43 char ch = s.charAt(i); 44 if (ch == '\\') { 45 if (++i >= len) { 46 throwIAE(s); 47 } 48 49 ch = s.charAt(i); 50 switch (ch) { 51 case 'n': 52 ch = '\n'; 53 break; 54 55 case 'r': 56 ch = '\r'; 57 break; 58 59 case 't': 60 ch = '\t'; 61 break; 62 63 case 'b': 64 ch = '\b'; 65 break; 66 67 case 'f': 68 ch = '\f'; 69 break; 70 71 case 'u': 72 int uEnd = ++i + 4; 73 if (uEnd > len) { 74 throwIAE(s); 75 } 76 77 int val = 0; 78 while (i < uEnd) { 79 ch = s.charAt(i++); 80 if (ch >= '0' && ch <= '9') { 81 val = (val << 4) + ch - '0'; 82 83 } else { 84 ch = Character.toLowerCase(ch); 85 if (ch >= 'a' && ch <= 'f') { 86 val = (val << 4) + 10 + ch - 'a'; 87 88 } else { 89 throw new IllegalArgumentException ( 90 "Malformed \\uxxxx encoding in string='" 91 + s + "'"); 92 } 93 } 94 } 95 ch = (char)val; 96 break; 97 98 default: 99 if (ch >= '0' && ch <= '7') { 101 val = ch - '0'; 102 int maxDigCnt = (val < 4) ? 2 : 1; 103 while (maxDigCnt-- > 0) { 104 ch = s.charAt(++i); 105 if (ch < '0' || ch > '7') { 106 i--; 107 break; 108 } 109 val = (val << 3) + (val - '0'); 110 } 111 ch = (char)val; 112 } 113 } 114 } 115 116 sb.append(ch); 117 } 118 119 return sb.toString(); 120 } 121 122 private static void throwIAE(String s) { 123 throw new IllegalArgumentException ("Unexpected end of string s='" + s + "'"); 124 } 125 126 static String toElementContent(String text) { 127 if (text == null) { 128 throw new NullPointerException (); 129 } 130 131 if (checkContentCharacters(text)) return text; 132 133 StringBuffer buf = new StringBuffer (); 134 135 for (int i = 0; i<text.length(); i++) { 136 char ch = text.charAt(i); 137 if ('<' == ch) { 138 buf.append("<"); 139 continue; 140 } else if ('&' == ch) { 141 buf.append("&"); 142 continue; 143 } else if ('>' == ch && i>1 && text.charAt(i-2) == ']' && text.charAt(i-1) == ']') { 144 buf.append(">"); 145 continue; 146 } 147 buf.append(ch); 148 } 149 return buf.toString(); 150 } 151 152 157 private static boolean checkContentCharacters(String chars) { 158 boolean escape = false; 159 for (int i = 0; i<chars.length(); i++) { 160 char ch = chars.charAt(i); 161 if (((int)ch) <= 93) { switch (ch) { 163 case 0x9: 164 case 0xA: 165 case 0xD: 166 continue; 167 case '>': if (escape) continue; 169 escape = i > 0 && (chars.charAt(i - 1) == ']'); 170 continue; 171 case '<': 172 case '&': 173 escape = true; 174 continue; 175 default: 176 if (((int) ch) < 0x20) { 177 throw new IllegalArgumentException ( 178 "Invalid XML character &#" + ((int)ch) + ";."); 179 } 180 } 181 } 182 } 183 return escape == false; 184 } 185 186 } 187 | Popular Tags |