KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > util > XMLEntityCodec


1 /*
2  * $Id: XMLEntityCodec.java 4219 2006-12-09 10:15:14Z lajos $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.util;
12
13 import java.io.IOException JavaDoc;
14 import java.io.Writer JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Map JavaDoc;
17
18 import org.apache.commons.lang.StringEscapeUtils;
19
20 /**
21  * This encoder contains methods that convert characters to Character entities as
22  * defined by http://www.w3.org/TR/REC-html40/sgml/entities.html. More precisely it
23  * combines the functionality of {@link StringEscapeUtils#escapeXml(String)} and
24  * {@link StringEscapeUtils#escapeHtml(String)} into a single pass.
25  */

26 // @ThreadSafe
27
public class XMLEntityCodec
28 {
29     private static final Entities MuleEntities = new Entities();
30
31     static
32     {
33         MuleEntities.addEntities(Entities.APOS_ARRAY);
34         MuleEntities.addEntities(Entities.BASIC_ARRAY);
35         MuleEntities.addEntities(Entities.ISO8859_1_ARRAY);
36         MuleEntities.addEntities(Entities.HTML40_ARRAY);
37     }
38
39     public static String JavaDoc encodeString(String JavaDoc str)
40     {
41         if (StringUtils.isEmpty(str))
42         {
43             return str;
44         }
45
46         return MuleEntities.escape(str);
47     }
48
49     public static String JavaDoc decodeString(String JavaDoc str)
50     {
51         if (StringUtils.isEmpty(str))
52         {
53             return str;
54         }
55
56         return MuleEntities.unescape(str);
57     }
58
59     /**
60      * <p>
61      * Returns the name of the entity identified by the specified value.
62      * </p>
63      *
64      * @param value the value to locate
65      * @return entity name associated with the specified value
66      */

67     public static String JavaDoc entityName(int value)
68     {
69         return MuleEntities.map.name(value);
70     }
71
72     /**
73      * <p>
74      * Returns the value of the entity identified by the specified name.
75      * </p>
76      *
77      * @param name the name to locate
78      * @return entity value associated with the specified name
79      */

80     public static int entityValue(String JavaDoc name)
81     {
82         return MuleEntities.map.value(name);
83     }
84
85
86     //
87
// everything from here on is copied from commons-lang 2.2 + svn since it is not
88
// extensible and referencing the package-private class can lead to classloader
89
// problems :-(
90
//
91

92     /*
93      * Licensed to the Apache Software Foundation (ASF) under one or more
94      * contributor license agreements. See the NOTICE file distributed with
95      * this work for additional information regarding copyright ownership.
96      * The ASF licenses this file to You under the Apache License, Version 2.0
97      * (the "License"); you may not use this file except in compliance with
98      * the License. You may obtain a copy of the License at
99      *
100      * http://www.apache.org/licenses/LICENSE-2.0
101      *
102      * Unless required by applicable law or agreed to in writing, software
103      * distributed under the License is distributed on an "AS IS" BASIS,
104      * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
105      * See the License for the specific language governing permissions and
106      * limitations under the License.
107      */

108
109     /**
110      * <p>Provides HTML and XML entity utilities.</p>
111      *
112      * @see <a HREF="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
113      * @see <a HREF="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
114      * @see <a HREF="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
115      * @see <a HREF="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
116      * @see <a HREF="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
117      *
118      * @author <a HREF="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
119      * @author <a HREF="mailto:ggregory@seagullsw.com">Gary Gregory</a>
120      * @since 2.0
121      * @version $Id: XMLEntityCodec.java 4219 2006-12-09 10:15:14Z lajos $
122      */

123     private static class Entities
124     {
125
126         private static final String JavaDoc[][] BASIC_ARRAY =
127         {
128             {"quot", "34"}, // " - double-quote
129
{"amp", "38"}, // & - ampersand
130
{"lt", "60"}, // < - less-than
131
{"gt", "62"}, // > - greater-than
132
};
133
134         private static final String JavaDoc[][] APOS_ARRAY =
135         {
136             {"apos", "39"}, // XML apostrophe
137
};
138
139         // package scoped for testing
140
static final String JavaDoc[][] ISO8859_1_ARRAY =
141         {
142             {"nbsp", "160"}, // non-breaking space
143
{"iexcl", "161"}, //inverted exclamation mark
144
{"cent", "162"}, //cent sign
145
{"pound", "163"}, //pound sign
146
{"curren", "164"}, //currency sign
147
{"yen", "165"}, //yen sign = yuan sign
148
{"brvbar", "166"}, //broken bar = broken vertical bar
149
{"sect", "167"}, //section sign
150
{"uml", "168"}, //diaeresis = spacing diaeresis
151
{"copy", "169"}, // © - copyright sign
152
{"ordf", "170"}, //feminine ordinal indicator
153
{"laquo", "171"}, //left-pointing double angle quotation mark = left pointing guillemet
154
{"not", "172"}, //not sign
155
{"shy", "173"}, //soft hyphen = discretionary hyphen
156
{"reg", "174"}, // ® - registered trademark sign
157
{"macr", "175"}, //macron = spacing macron = overline = APL overbar
158
{"deg", "176"}, //degree sign
159
{"plusmn", "177"}, //plus-minus sign = plus-or-minus sign
160
{"sup2", "178"}, //superscript two = superscript digit two = squared
161
{"sup3", "179"}, //superscript three = superscript digit three = cubed
162
{"acute", "180"}, //acute accent = spacing acute
163
{"micro", "181"}, //micro sign
164
{"para", "182"}, //pilcrow sign = paragraph sign
165
{"middot", "183"}, //middle dot = Georgian comma = Greek middle dot
166
{"cedil", "184"}, //cedilla = spacing cedilla
167
{"sup1", "185"}, //superscript one = superscript digit one
168
{"ordm", "186"}, //masculine ordinal indicator
169
{"raquo", "187"}, //right-pointing double angle quotation mark = right pointing guillemet
170
{"frac14", "188"}, //vulgar fraction one quarter = fraction one quarter
171
{"frac12", "189"}, //vulgar fraction one half = fraction one half
172
{"frac34", "190"}, //vulgar fraction three quarters = fraction three quarters
173
{"iquest", "191"}, //inverted question mark = turned question mark
174
{"Agrave", "192"}, // À - uppercase A, grave accent
175
{"Aacute", "193"}, // Á - uppercase A, acute accent
176
{"Acirc", "194"}, // Â - uppercase A, circumflex accent
177
{"Atilde", "195"}, // Ã - uppercase A, tilde
178
{"Auml", "196"}, // Ä - uppercase A, umlaut
179
{"Aring", "197"}, // Å - uppercase A, ring
180
{"AElig", "198"}, // Æ - uppercase AE
181
{"Ccedil", "199"}, // Ç - uppercase C, cedilla
182
{"Egrave", "200"}, // È - uppercase E, grave accent
183
{"Eacute", "201"}, // É - uppercase E, acute accent
184
{"Ecirc", "202"}, // Ê - uppercase E, circumflex accent
185
{"Euml", "203"}, // Ë - uppercase E, umlaut
186
{"Igrave", "204"}, // Ì - uppercase I, grave accent
187
{"Iacute", "205"}, // Í - uppercase I, acute accent
188
{"Icirc", "206"}, // Î - uppercase I, circumflex accent
189
{"Iuml", "207"}, // Ï - uppercase I, umlaut
190
{"ETH", "208"}, // Ð - uppercase Eth, Icelandic
191
{"Ntilde", "209"}, // Ñ - uppercase N, tilde
192
{"Ograve", "210"}, // Ò - uppercase O, grave accent
193
{"Oacute", "211"}, // Ó - uppercase O, acute accent
194
{"Ocirc", "212"}, // Ô - uppercase O, circumflex accent
195
{"Otilde", "213"}, // Õ - uppercase O, tilde
196
{"Ouml", "214"}, // Ö - uppercase O, umlaut
197
{"times", "215"}, //multiplication sign
198
{"Oslash", "216"}, // Ø - uppercase O, slash
199
{"Ugrave", "217"}, // Ù - uppercase U, grave accent
200
{"Uacute", "218"}, // Ú - uppercase U, acute accent
201
{"Ucirc", "219"}, // Û - uppercase U, circumflex accent
202
{"Uuml", "220"}, // Ü - uppercase U, umlaut
203
{"Yacute", "221"}, // Ý - uppercase Y, acute accent
204
{"THORN", "222"}, // Þ - uppercase THORN, Icelandic
205
{"szlig", "223"}, // ß - lowercase sharps, German
206
{"agrave", "224"}, // à - lowercase a, grave accent
207
{"aacute", "225"}, // á - lowercase a, acute accent
208
{"acirc", "226"}, // â - lowercase a, circumflex accent
209
{"atilde", "227"}, // ã - lowercase a, tilde
210
{"auml", "228"}, // ä - lowercase a, umlaut
211
{"aring", "229"}, // å - lowercase a, ring
212
{"aelig", "230"}, // æ - lowercase ae
213
{"ccedil", "231"}, // ç - lowercase c, cedilla
214
{"egrave", "232"}, // è - lowercase e, grave accent
215
{"eacute", "233"}, // é - lowercase e, acute accent
216
{"ecirc", "234"}, // ê - lowercase e, circumflex accent
217
{"euml", "235"}, // ë - lowercase e, umlaut
218
{"igrave", "236"}, // ì - lowercase i, grave accent
219
{"iacute", "237"}, // í - lowercase i, acute accent
220
{"icirc", "238"}, // î - lowercase i, circumflex accent
221
{"iuml", "239"}, // ï - lowercase i, umlaut
222
{"eth", "240"}, // ð - lowercase eth, Icelandic
223
{"ntilde", "241"}, // ñ - lowercase n, tilde
224
{"ograve", "242"}, // ò - lowercase o, grave accent
225
{"oacute", "243"}, // ó - lowercase o, acute accent
226
{"ocirc", "244"}, // ô - lowercase o, circumflex accent
227
{"otilde", "245"}, // õ - lowercase o, tilde
228
{"ouml", "246"}, // ö - lowercase o, umlaut
229
{"divide", "247"}, // division sign
230
{"oslash", "248"}, // ø - lowercase o, slash
231
{"ugrave", "249"}, // ù - lowercase u, grave accent
232
{"uacute", "250"}, // ú - lowercase u, acute accent
233
{"ucirc", "251"}, // û - lowercase u, circumflex accent
234
{"uuml", "252"}, // ü - lowercase u, umlaut
235
{"yacute", "253"}, // ý - lowercase y, acute accent
236
{"thorn", "254"}, // þ - lowercase thorn, Icelandic
237
{"yuml", "255"}, // ÿ - lowercase y, umlaut
238
};
239
240         // http://www.w3.org/TR/REC-html40/sgml/entities.html
241
// package scoped for testing
242
static final String JavaDoc[][] HTML40_ARRAY =
243         {
244 // <!-- Latin Extended-B -->
245
{"fnof", "402"}, //latin small f with hook = function= florin, U+0192 ISOtech -->
246
// <!-- Greek -->
247
{"Alpha", "913"}, //greek capital letter alpha, U+0391 -->
248
{"Beta", "914"}, //greek capital letter beta, U+0392 -->
249
{"Gamma", "915"}, //greek capital letter gamma,U+0393 ISOgrk3 -->
250
{"Delta", "916"}, //greek capital letter delta,U+0394 ISOgrk3 -->
251
{"Epsilon", "917"}, //greek capital letter epsilon, U+0395 -->
252
{"Zeta", "918"}, //greek capital letter zeta, U+0396 -->
253
{"Eta", "919"}, //greek capital letter eta, U+0397 -->
254
{"Theta", "920"}, //greek capital letter theta,U+0398 ISOgrk3 -->
255
{"Iota", "921"}, //greek capital letter iota, U+0399 -->
256
{"Kappa", "922"}, //greek capital letter kappa, U+039A -->
257
{"Lambda", "923"}, //greek capital letter lambda,U+039B ISOgrk3 -->
258
{"Mu", "924"}, //greek capital letter mu, U+039C -->
259
{"Nu", "925"}, //greek capital letter nu, U+039D -->
260
{"Xi", "926"}, //greek capital letter xi, U+039E ISOgrk3 -->
261
{"Omicron", "927"}, //greek capital letter omicron, U+039F -->
262
{"Pi", "928"}, //greek capital letter pi, U+03A0 ISOgrk3 -->
263
{"Rho", "929"}, //greek capital letter rho, U+03A1 -->
264
// <!-- there is no Sigmaf, and no U+03A2 character either -->
265
{"Sigma", "931"}, //greek capital letter sigma,U+03A3 ISOgrk3 -->
266
{"Tau", "932"}, //greek capital letter tau, U+03A4 -->
267
{"Upsilon", "933"}, //greek capital letter upsilon,U+03A5 ISOgrk3 -->
268
{"Phi", "934"}, //greek capital letter phi,U+03A6 ISOgrk3 -->
269
{"Chi", "935"}, //greek capital letter chi, U+03A7 -->
270
{"Psi", "936"}, //greek capital letter psi,U+03A8 ISOgrk3 -->
271
{"Omega", "937"}, //greek capital letter omega,U+03A9 ISOgrk3 -->
272
{"alpha", "945"}, //greek small letter alpha,U+03B1 ISOgrk3 -->
273
{"beta", "946"}, //greek small letter beta, U+03B2 ISOgrk3 -->
274
{"gamma", "947"}, //greek small letter gamma,U+03B3 ISOgrk3 -->
275
{"delta", "948"}, //greek small letter delta,U+03B4 ISOgrk3 -->
276
{"epsilon", "949"}, //greek small letter epsilon,U+03B5 ISOgrk3 -->
277
{"zeta", "950"}, //greek small letter zeta, U+03B6 ISOgrk3 -->
278
{"eta", "951"}, //greek small letter eta, U+03B7 ISOgrk3 -->
279
{"theta", "952"}, //greek small letter theta,U+03B8 ISOgrk3 -->
280
{"iota", "953"}, //greek small letter iota, U+03B9 ISOgrk3 -->
281
{"kappa", "954"}, //greek small letter kappa,U+03BA ISOgrk3 -->
282
{"lambda", "955"}, //greek small letter lambda,U+03BB ISOgrk3 -->
283
{"mu", "956"}, //greek small letter mu, U+03BC ISOgrk3 -->
284
{"nu", "957"}, //greek small letter nu, U+03BD ISOgrk3 -->
285
{"xi", "958"}, //greek small letter xi, U+03BE ISOgrk3 -->
286
{"omicron", "959"}, //greek small letter omicron, U+03BF NEW -->
287
{"pi", "960"}, //greek small letter pi, U+03C0 ISOgrk3 -->
288
{"rho", "961"}, //greek small letter rho, U+03C1 ISOgrk3 -->
289
{"sigmaf", "962"}, //greek small letter final sigma,U+03C2 ISOgrk3 -->
290
{"sigma", "963"}, //greek small letter sigma,U+03C3 ISOgrk3 -->
291
{"tau", "964"}, //greek small letter tau, U+03C4 ISOgrk3 -->
292
{"upsilon", "965"}, //greek small letter upsilon,U+03C5 ISOgrk3 -->
293
{"phi", "966"}, //greek small letter phi, U+03C6 ISOgrk3 -->
294
{"chi", "967"}, //greek small letter chi, U+03C7 ISOgrk3 -->
295
{"psi", "968"}, //greek small letter psi, U+03C8 ISOgrk3 -->
296
{"omega", "969"}, //greek small letter omega,U+03C9 ISOgrk3 -->
297
{"thetasym", "977"}, //greek small letter theta symbol,U+03D1 NEW -->
298
{"upsih", "978"}, //greek upsilon with hook symbol,U+03D2 NEW -->
299
{"piv", "982"}, //greek pi symbol, U+03D6 ISOgrk3 -->
300
// <!-- General Punctuation -->
301
{"bull", "8226"}, //bullet = black small circle,U+2022 ISOpub -->
302
// <!-- bullet is NOT the same as bullet operator, U+2219 -->
303
{"hellip", "8230"}, //horizontal ellipsis = three dot leader,U+2026 ISOpub -->
304
{"prime", "8242"}, //prime = minutes = feet, U+2032 ISOtech -->
305
{"Prime", "8243"}, //double prime = seconds = inches,U+2033 ISOtech -->
306
{"oline", "8254"}, //overline = spacing overscore,U+203E NEW -->
307
{"frasl", "8260"}, //fraction slash, U+2044 NEW -->
308
// <!-- Letterlike Symbols -->
309
{"weierp", "8472"}, //script capital P = power set= Weierstrass p, U+2118 ISOamso -->
310
{"image", "8465"}, //blackletter capital I = imaginary part,U+2111 ISOamso -->
311
{"real", "8476"}, //blackletter capital R = real part symbol,U+211C ISOamso -->
312
{"trade", "8482"}, //trade mark sign, U+2122 ISOnum -->
313
{"alefsym", "8501"}, //alef symbol = first transfinite cardinal,U+2135 NEW -->
314
// <!-- alef symbol is NOT the same as hebrew letter alef,U+05D0 although the
315
// same glyph could be used to depict both characters -->
316
// <!-- Arrows -->
317
{"larr", "8592"}, //leftwards arrow, U+2190 ISOnum -->
318
{"uarr", "8593"}, //upwards arrow, U+2191 ISOnum-->
319
{"rarr", "8594"}, //rightwards arrow, U+2192 ISOnum -->
320
{"darr", "8595"}, //downwards arrow, U+2193 ISOnum -->
321
{"harr", "8596"}, //left right arrow, U+2194 ISOamsa -->
322
{"crarr", "8629"}, //downwards arrow with corner leftwards= carriage return, U+21B5 NEW -->
323
{"lArr", "8656"}, //leftwards double arrow, U+21D0 ISOtech -->
324
// <!-- ISO 10646 does not say that lArr is the same as the 'is implied by'
325
// arrow but also does not have any other character for that function.
326
// So ? lArr canbe used for 'is implied by' as ISOtech suggests -->
327
{"uArr", "8657"}, //upwards double arrow, U+21D1 ISOamsa -->
328
{"rArr", "8658"}, //rightwards double arrow,U+21D2 ISOtech -->
329
// <!-- ISO 10646 does not say this is the 'implies' character but does not
330
// have another character with this function so ?rArr can be used for
331
// 'implies' as ISOtech suggests -->
332
{"dArr", "8659"}, //downwards double arrow, U+21D3 ISOamsa -->
333
{"hArr", "8660"}, //left right double arrow,U+21D4 ISOamsa -->
334
// <!-- Mathematical Operators -->
335
{"forall", "8704"}, //for all, U+2200 ISOtech -->
336
{"part", "8706"}, //partial differential, U+2202 ISOtech -->
337
{"exist", "8707"}, //there exists, U+2203 ISOtech -->
338
{"empty", "8709"}, //empty set = null set = diameter,U+2205 ISOamso -->
339
{"nabla", "8711"}, //nabla = backward difference,U+2207 ISOtech -->
340
{"isin", "8712"}, //element of, U+2208 ISOtech -->
341
{"notin", "8713"}, //not an element of, U+2209 ISOtech -->
342
{"ni", "8715"}, //contains as member, U+220B ISOtech -->
343
// <!-- should there be a more memorable name than 'ni'? -->
344
{"prod", "8719"}, //n-ary product = product sign,U+220F ISOamsb -->
345
// <!-- prod is NOT the same character as U+03A0 'greek capital letter pi'
346
// though the same glyph might be used for both -->
347
{"sum", "8721"}, //n-ary summation, U+2211 ISOamsb -->
348
// <!-- sum is NOT the same character as U+03A3 'greek capital letter sigma'
349
// though the same glyph might be used for both -->
350
{"minus", "8722"}, //minus sign, U+2212 ISOtech -->
351
{"lowast", "8727"}, //asterisk operator, U+2217 ISOtech -->
352
{"radic", "8730"}, //square root = radical sign,U+221A ISOtech -->
353
{"prop", "8733"}, //proportional to, U+221D ISOtech -->
354
{"infin", "8734"}, //infinity, U+221E ISOtech -->
355
{"ang", "8736"}, //angle, U+2220 ISOamso -->
356
{"and", "8743"}, //logical and = wedge, U+2227 ISOtech -->
357
{"or", "8744"}, //logical or = vee, U+2228 ISOtech -->
358
{"cap", "8745"}, //intersection = cap, U+2229 ISOtech -->
359
{"cup", "8746"}, //union = cup, U+222A ISOtech -->
360
{"int", "8747"}, //integral, U+222B ISOtech -->
361
{"there4", "8756"}, //therefore, U+2234 ISOtech -->
362
{"sim", "8764"}, //tilde operator = varies with = similar to,U+223C ISOtech -->
363
// <!-- tilde operator is NOT the same character as the tilde, U+007E,although
364
// the same glyph might be used to represent both -->
365
{"cong", "8773"}, //approximately equal to, U+2245 ISOtech -->
366
{"asymp", "8776"}, //almost equal to = asymptotic to,U+2248 ISOamsr -->
367
{"ne", "8800"}, //not equal to, U+2260 ISOtech -->
368
{"equiv", "8801"}, //identical to, U+2261 ISOtech -->
369
{"le", "8804"}, //less-than or equal to, U+2264 ISOtech -->
370
{"ge", "8805"}, //greater-than or equal to,U+2265 ISOtech -->
371
{"sub", "8834"}, //subset of, U+2282 ISOtech -->
372
{"sup", "8835"}, //superset of, U+2283 ISOtech -->
373
// <!-- note that nsup, 'not a superset of, U+2283' is not covered by the
374
// Symbol font encoding and is not included. Should it be, for symmetry?
375
// It is in ISOamsn --> <!ENTITY nsub", "8836"},
376
// not a subset of, U+2284 ISOamsn -->
377
{"sube", "8838"}, //subset of or equal to, U+2286 ISOtech -->
378
{"supe", "8839"}, //superset of or equal to,U+2287 ISOtech -->
379
{"oplus", "8853"}, //circled plus = direct sum,U+2295 ISOamsb -->
380
{"otimes", "8855"}, //circled times = vector product,U+2297 ISOamsb -->
381
{"perp", "8869"}, //up tack = orthogonal to = perpendicular,U+22A5 ISOtech -->
382
{"sdot", "8901"}, //dot operator, U+22C5 ISOamsb -->
383
// <!-- dot operator is NOT the same character as U+00B7 middle dot -->
384
// <!-- Miscellaneous Technical -->
385
{"lceil", "8968"}, //left ceiling = apl upstile,U+2308 ISOamsc -->
386
{"rceil", "8969"}, //right ceiling, U+2309 ISOamsc -->
387
{"lfloor", "8970"}, //left floor = apl downstile,U+230A ISOamsc -->
388
{"rfloor", "8971"}, //right floor, U+230B ISOamsc -->
389
{"lang", "9001"}, //left-pointing angle bracket = bra,U+2329 ISOtech -->
390
// <!-- lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation mark' -->
391
{"rang", "9002"}, //right-pointing angle bracket = ket,U+232A ISOtech -->
392
// <!-- rang is NOT the same character as U+003E 'greater than' or U+203A
393
// 'single right-pointing angle quotation mark' -->
394
// <!-- Geometric Shapes -->
395
{"loz", "9674"}, //lozenge, U+25CA ISOpub -->
396
// <!-- Miscellaneous Symbols -->
397
{"spades", "9824"}, //black spade suit, U+2660 ISOpub -->
398
// <!-- black here seems to mean filled as opposed to hollow -->
399
{"clubs", "9827"}, //black club suit = shamrock,U+2663 ISOpub -->
400
{"hearts", "9829"}, //black heart suit = valentine,U+2665 ISOpub -->
401
{"diams", "9830"}, //black diamond suit, U+2666 ISOpub -->
402

403 // <!-- Latin Extended-A -->
404
{"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 -->
405
{"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 -->
406
// <!-- ligature is a misnomer, this is a separate character in some languages -->
407
{"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 -->
408
{"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 -->
409
{"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 -->
410
// <!-- Spacing Modifier Letters -->
411
{"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub -->
412
{"tilde", "732"}, //small tilde, U+02DC ISOdia -->
413
// <!-- General Punctuation -->
414
{"ensp", "8194"}, //en space, U+2002 ISOpub -->
415
{"emsp", "8195"}, //em space, U+2003 ISOpub -->
416
{"thinsp", "8201"}, //thin space, U+2009 ISOpub -->
417
{"zwnj", "8204"}, //zero width non-joiner,U+200C NEW RFC 2070 -->
418
{"zwj", "8205"}, //zero width joiner, U+200D NEW RFC 2070 -->
419
{"lrm", "8206"}, //left-to-right mark, U+200E NEW RFC 2070 -->
420
{"rlm", "8207"}, //right-to-left mark, U+200F NEW RFC 2070 -->
421
{"ndash", "8211"}, //en dash, U+2013 ISOpub -->
422
{"mdash", "8212"}, //em dash, U+2014 ISOpub -->
423
{"lsquo", "8216"}, //left single quotation mark,U+2018 ISOnum -->
424
{"rsquo", "8217"}, //right single quotation mark,U+2019 ISOnum -->
425
{"sbquo", "8218"}, //single low-9 quotation mark, U+201A NEW -->
426
{"ldquo", "8220"}, //left double quotation mark,U+201C ISOnum -->
427
{"rdquo", "8221"}, //right double quotation mark,U+201D ISOnum -->
428
{"bdquo", "8222"}, //double low-9 quotation mark, U+201E NEW -->
429
{"dagger", "8224"}, //dagger, U+2020 ISOpub -->
430
{"Dagger", "8225"}, //double dagger, U+2021 ISOpub -->
431
{"permil", "8240"}, //per mille sign, U+2030 ISOtech -->
432
{"lsaquo", "8249"}, //single left-pointing angle quotation mark,U+2039 ISO proposed -->
433
// <!-- lsaquo is proposed but not yet ISO standardized -->
434
{"rsaquo", "8250"}, //single right-pointing angle quotation mark,U+203A ISO proposed -->
435
// <!-- rsaquo is proposed but not yet ISO standardized -->
436
{"euro", "8364"}, // -- euro sign, U+20AC NEW -->
437
};
438
439         // package scoped for testing
440
private EntityMap map = new Entities.LookupEntityMap();
441
442         /**
443          * <p>
444          * Adds entities to this entity.
445          * </p>
446          *
447          * @param entityArray array of entities to be added
448          */

449         public void addEntities(String JavaDoc[][] entityArray)
450         {
451             for (int i = 0; i < entityArray.length; ++i)
452             {
453                 addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1]));
454             }
455         }
456
457         /**
458          * <p>
459          * Add an entity to this entity.
460          * </p>
461          *
462          * @param name name of the entity
463          * @param value vale of the entity
464          */

465         public void addEntity(String JavaDoc name, int value)
466         {
467             map.add(name, value);
468         }
469
470         /**
471          * <p>
472          * Returns the name of the entity identified by the specified value.
473          * </p>
474          *
475          * @param value the value to locate
476          * @return entity name associated with the specified value
477          */

478         public String JavaDoc entityName(int value)
479         {
480             return map.name(value);
481         }
482
483         /**
484          * <p>
485          * Returns the value of the entity identified by the specified name.
486          * </p>
487          *
488          * @param name the name to locate
489          * @return entity value associated with the specified name
490          */

491         public int entityValue(String JavaDoc name)
492         {
493             return map.value(name);
494         }
495
496         /**
497          * <p>
498          * Escapes the characters in a <code>String</code>.
499          * </p>
500          * <p>
501          * For example, if you have called addEntity(&quot;foo&quot;, 0xA1),
502          * escape(&quot;¡&quot;) will return &quot;&amp;foo;&quot;
503          * </p>
504          *
505          * @param str The <code>String</code> to escape.
506          * @return A new escaped <code>String</code>.
507          */

508         public String JavaDoc escape(String JavaDoc str)
509         {
510             // todo: rewrite to use a Writer
511
StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str.length() * 2);
512             for (int i = 0; i < str.length(); ++i)
513             {
514                 char ch = str.charAt(i);
515                 String JavaDoc entityName = this.entityName(ch);
516                 if (entityName == null)
517                 {
518                     if (ch > 0x7F)
519                     {
520                         buf.append('&');
521                         buf.append('#');
522                         buf.append((int)ch);
523                         buf.append(';');
524                     }
525                     else
526                     {
527                         buf.append(ch);
528                     }
529                 }
530                 else
531                 {
532                     buf.append('&');
533                     buf.append(entityName);
534                     buf.append(';');
535                 }
536             }
537             return buf.toString();
538         }
539
540         /**
541          * <p>
542          * Escapes the characters in the <code>String</code> passed and writes the
543          * result to the <code>Writer</code> passed.
544          * </p>
545          *
546          * @param writer The <code>Writer</code> to write the results of the
547          * escaping to. Assumed to be a non-null value.
548          * @param str The <code>String</code> to escape. Assumed to be a non-null
549          * value.
550          * @throws IOException when <code>Writer</code> passed throws the exception
551          * from calls to the {@link Writer#write(int)} methods.
552          * @see #escape(String)
553          * @see Writer
554          */

555         public void escape(Writer JavaDoc writer, String JavaDoc str) throws IOException JavaDoc
556         {
557             int len = str.length();
558             for (int i = 0; i < len; i++)
559             {
560                 char c = str.charAt(i);
561                 String JavaDoc entityName = this.entityName(c);
562                 if (entityName == null)
563                 {
564                     if (c > 0x7F)
565                     {
566                         writer.write("&#");
567                         writer.write(Integer.toString(c, 10));
568                         writer.write(';');
569                     }
570                     else
571                     {
572                         writer.write(c);
573                     }
574                 }
575                 else
576                 {
577                     writer.write('&');
578                     writer.write(entityName);
579                     writer.write(';');
580                 }
581             }
582         }
583
584         /**
585          * <p>
586          * Unescapes the entities in a <code>String</code>.
587          * </p>
588          * <p>
589          * For example, if you have called addEntity(&quot;foo&quot;, 0xA1),
590          * unescape(&quot;&amp;foo;&quot;) will return &quot;¡&quot;
591          * </p>
592          *
593          * @param str The <code>String</code> to escape.
594          * @return A new escaped <code>String</code> or str itself if no unescaping
595          * was necessary.
596          */

597         public String JavaDoc unescape(String JavaDoc str)
598         {
599             int firstAmp = str.indexOf('&');
600             if (firstAmp < 0)
601             {
602                 return str;
603             }
604
605             StringBuffer JavaDoc buf = new StringBuffer JavaDoc(str.length());
606             buf.append(str.substring(0, firstAmp));
607             for (int i = firstAmp; i < str.length(); ++i)
608             {
609                 char ch = str.charAt(i);
610                 if (ch == '&')
611                 {
612                     int semi = str.indexOf(';', i + 1);
613                     if (semi == -1)
614                     {
615                         buf.append(ch);
616                         continue;
617                     }
618                     int amph = str.indexOf('&', i + 1);
619                     if (amph != -1 && amph < semi)
620                     {
621                         // Then the text looks like &...&...;
622
buf.append(ch);
623                         continue;
624                     }
625                     String JavaDoc entityName = str.substring(i + 1, semi);
626                     int entityValue;
627                     if (entityName.length() == 0)
628                     {
629                         entityValue = -1;
630                     }
631                     else if (entityName.charAt(0) == '#')
632                     {
633                         if (entityName.length() == 1)
634                         {
635                             entityValue = -1;
636                         }
637                         else
638                         {
639                             char charAt1 = entityName.charAt(1);
640                             try
641                             {
642                                 if (charAt1 == 'x' || charAt1 == 'X')
643                                 {
644                                     entityValue = Integer.valueOf(entityName.substring(2), 16).intValue();
645                                 }
646                                 else
647                                 {
648                                     entityValue = Integer.parseInt(entityName.substring(1));
649                                 }
650                                 if (entityValue > 0xFFFF)
651                                 {
652                                     entityValue = -1;
653                                 }
654                             }
655                             catch (NumberFormatException JavaDoc ex)
656                             {
657                                 entityValue = -1;
658                             }
659                         }
660                     }
661                     else
662                     {
663                         entityValue = this.entityValue(entityName);
664                     }
665                     if (entityValue == -1)
666                     {
667                         buf.append('&');
668                         buf.append(entityName);
669                         buf.append(';');
670                     }
671                     else
672                     {
673                         buf.append((char)(entityValue));
674                     }
675                     i = semi;
676                 }
677                 else
678                 {
679                     buf.append(ch);
680                 }
681             }
682             return buf.toString();
683         }
684
685         /**
686          * <p>
687          * Unescapes the escaped entities in the <code>String</code> passed and
688          * writes the result to the <code>Writer</code> passed.
689          * </p>
690          *
691          * @param writer The <code>Writer</code> to write the results to; assumed
692          * to be non-null.
693          * @param string The <code>String</code> to write the results to; assumed
694          * to be non-null.
695          * @throws IOException when <code>Writer</code> passed throws the exception
696          * from calls to the {@link Writer#write(int)} methods.
697          * @see #escape(String)
698          * @see Writer
699          */

700         public void unescape(Writer JavaDoc writer, String JavaDoc string) throws IOException JavaDoc
701         {
702             int firstAmp = string.indexOf('&');
703             if (firstAmp < 0)
704             {
705                 writer.write(string);
706                 return;
707             }
708
709             writer.write(string, 0, firstAmp);
710             int len = string.length();
711             for (int i = firstAmp; i < len; i++)
712             {
713                 char c = string.charAt(i);
714                 if (c == '&')
715                 {
716                     int nextIdx = i + 1;
717                     int semiColonIdx = string.indexOf(';', nextIdx);
718                     if (semiColonIdx == -1)
719                     {
720                         writer.write(c);
721                         continue;
722                     }
723                     int amphersandIdx = string.indexOf('&', i + 1);
724                     if (amphersandIdx != -1 && amphersandIdx < semiColonIdx)
725                     {
726                         // Then the text looks like &...&...;
727
writer.write(c);
728                         continue;
729                     }
730                     String JavaDoc entityContent = string.substring(nextIdx, semiColonIdx);
731                     int entityValue = -1;
732                     int entityContentLen = entityContent.length();
733                     if (entityContentLen > 0)
734                     {
735                         if (entityContent.charAt(0) == '#')
736                         { // escaped value content is an integer (decimal or
737
// hexidecimal)
738
if (entityContentLen > 1)
739                             {
740                                 char isHexChar = entityContent.charAt(1);
741                                 try
742                                 {
743                                     switch (isHexChar)
744                                     {
745                                         case 'X' :
746                                         case 'x' :
747                                         {
748                                             entityValue = Integer.parseInt(entityContent.substring(2), 16);
749                                             break;
750                                         }
751                                         default :
752                                         {
753                                             entityValue = Integer.parseInt(entityContent.substring(1), 10);
754                                         }
755                                     }
756                                     if (entityValue > 0xFFFF)
757                                     {
758                                         entityValue = -1;
759                                     }
760                                 }
761                                 catch (NumberFormatException JavaDoc e)
762                                 {
763                                     entityValue = -1;
764                                 }
765                             }
766                         }
767                         else
768                         { // escaped value content is an entity name
769
entityValue = this.entityValue(entityContent);
770                         }
771                     }
772
773                     if (entityValue == -1)
774                     {
775                         writer.write('&');
776                         writer.write(entityContent);
777                         writer.write(';');
778                     }
779                     else
780                     {
781                         writer.write(entityValue);
782                     }
783                     i = semiColonIdx; // move index up to the semi-colon
784
}
785                 else
786                 {
787                     writer.write(c);
788                 }
789             }
790         }
791         
792         private static interface EntityMap
793         {
794             /**
795              * <p>
796              * Add an entry to this entity map.
797              * </p>
798              *
799              * @param name the entity name
800              * @param value the entity value
801              */

802             void add(String JavaDoc name, int value);
803
804             /**
805              * <p>
806              * Returns the name of the entity identified by the specified value.
807              * </p>
808              *
809              * @param value the value to locate
810              * @return entity name associated with the specified value
811              */

812             String JavaDoc name(int value);
813
814             /**
815              * <p>
816              * Returns the value of the entity identified by the specified name.
817              * </p>
818              *
819              * @param name the name to locate
820              * @return entity value associated with the specified name
821              */

822             int value(String JavaDoc name);
823         }
824
825         private static class PrimitiveEntityMap implements EntityMap
826         {
827             private Map JavaDoc mapNameToValue = new HashMap JavaDoc();
828             private IntHashMap mapValueToName = new IntHashMap();
829
830             /**
831              * {@inheritDoc}
832              */

833             public void add(String JavaDoc name, int value)
834             {
835                 mapNameToValue.put(name, new Integer JavaDoc(value));
836                 mapValueToName.put(value, name);
837             }
838
839             /**
840              * {@inheritDoc}
841              */

842             public String JavaDoc name(int value)
843             {
844                 return (String JavaDoc)mapValueToName.get(value);
845             }
846
847             /**
848              * {@inheritDoc}
849              */

850             public int value(String JavaDoc name)
851             {
852                 Object JavaDoc value = mapNameToValue.get(name);
853                 if (value == null)
854                 {
855                     return -1;
856                 }
857                 return ((Integer JavaDoc)value).intValue();
858             }
859         }
860
861         private static class LookupEntityMap extends PrimitiveEntityMap
862         {
863             private String JavaDoc[] lookupTable;
864             private int LOOKUP_TABLE_SIZE = 256;
865
866             /**
867              * {@inheritDoc}
868              */

869             public String JavaDoc name(int value)
870             {
871                 if (value < LOOKUP_TABLE_SIZE)
872                 {
873                     return lookupTable()[value];
874                 }
875                 return super.name(value);
876             }
877
878             /**
879              * <p>
880              * Returns the lookup table for this entity map. The lookup table is
881              * created if it has not been previously.
882              * </p>
883              *
884              * @return the lookup table
885              */

886             private String JavaDoc[] lookupTable()
887             {
888                 if (lookupTable == null)
889                 {
890                     createLookupTable();
891                 }
892                 return lookupTable;
893             }
894
895             /**
896              * <p>
897              * Creates an entity lookup table of LOOKUP_TABLE_SIZE elements,
898              * initialized with entity names.
899              * </p>
900              */

901             private void createLookupTable()
902             {
903                 lookupTable = new String JavaDoc[LOOKUP_TABLE_SIZE];
904                 for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i)
905                 {
906                     lookupTable[i] = super.name(i);
907                 }
908             }
909         }
910
911         /**
912          * <p>
913          * A hash map that uses primitive ints for the key rather than objects.
914          * </p>
915          * <p>
916          * Note that this class is for internal optimization purposes only, and may
917          * not be supported in future releases of Jakarta Commons Lang. Utilities of
918          * this sort may be included in future releases of Jakarta Commons
919          * Collections.
920          * </p>
921          *
922          * @author Justin Couch
923          * @author Alex Chaffee (alex@apache.org)
924          * @author Stephen Colebourne
925          * @since 2.0
926          * @version $Revision: 4219 $
927          * @see java.util.HashMap
928          */

929         private static class IntHashMap
930         {
931
932             /**
933              * The hash table data.
934              */

935             private transient Entry table[];
936
937             /**
938              * The total number of entries in the hash table.
939              */

940             private transient int count;
941
942             /**
943              * The table is rehashed when its size exceeds this threshold. (The value
944              * of this field is (int)(capacity * loadFactor).)
945              *
946              * @serial
947              */

948             private int threshold;
949
950             /**
951              * The load factor for the hashtable.
952              *
953              * @serial
954              */

955             private float loadFactor;
956
957             /**
958              * <p>
959              * Innerclass that acts as a datastructure to create a new entry in the
960              * table.
961              * </p>
962              */

963             private static class Entry
964             {
965                 int hash;
966                 int key;
967                 Object JavaDoc value;
968                 Entry next;
969
970                 /**
971                  * <p>
972                  * Create a new entry with the given values.
973                  * </p>
974                  *
975                  * @param hash The code used to hash the object with
976                  * @param key The key used to enter this in the table
977                  * @param value The value for this key
978                  * @param next A reference to the next entry in the table
979                  */

980                 protected Entry(int hash, int key, Object JavaDoc value, Entry next)
981                 {
982                     this.hash = hash;
983                     this.key = key;
984                     this.value = value;
985                     this.next = next;
986                 }
987             }
988
989             /**
990              * <p>
991              * Constructs a new, empty hashtable with a default capacity and load
992              * factor, which is <code>20</code> and <code>0.75</code>
993              * respectively.
994              * </p>
995              */

996             public IntHashMap()
997             {
998                 this(20, 0.75f);
999             }
1000
1001            /**
1002             * <p>
1003             * Constructs a new, empty hashtable with the specified initial capacity
1004             * and default load factor, which is <code>0.75</code>.
1005             * </p>
1006             *
1007             * @param initialCapacity the initial capacity of the hashtable.
1008             * @throws IllegalArgumentException if the initial capacity is less than
1009             * zero.
1010             */

1011            public IntHashMap(int initialCapacity)
1012            {
1013                this(initialCapacity, 0.75f);
1014            }
1015
1016            /**
1017             * <p>
1018             * Constructs a new, empty hashtable with the specified initial capacity
1019             * and the specified load factor.
1020             * </p>
1021             *
1022             * @param initialCapacity the initial capacity of the hashtable.
1023             * @param loadFactor the load factor of the hashtable.
1024             * @throws IllegalArgumentException if the initial capacity is less than
1025             * zero, or if the load factor is nonpositive.
1026             */

1027            public IntHashMap(int initialCapacity, float loadFactor)
1028            {
1029                super();
1030                if (initialCapacity < 0)
1031                {
1032                    throw new IllegalArgumentException JavaDoc("Illegal Capacity: " + initialCapacity);
1033                }
1034                if (loadFactor <= 0)
1035                {
1036                    throw new IllegalArgumentException JavaDoc("Illegal Load: " + loadFactor);
1037                }
1038                if (initialCapacity == 0)
1039                {
1040                    initialCapacity = 1;
1041                }
1042
1043                this.loadFactor = loadFactor;
1044                table = new Entry[initialCapacity];
1045                threshold = (int)(initialCapacity * loadFactor);
1046            }
1047
1048            /**
1049             * <p>
1050             * Returns the number of keys in this hashtable.
1051             * </p>
1052             *
1053             * @return the number of keys in this hashtable.
1054             */

1055            public int size()
1056            {
1057                return count;
1058            }
1059
1060            /**
1061             * <p>
1062             * Tests if this hashtable maps no keys to values.
1063             * </p>
1064             *
1065             * @return <code>true</code> if this hashtable maps no keys to values;
1066             * <code>false</code> otherwise.
1067             */

1068            public boolean isEmpty()
1069            {
1070                return count == 0;
1071            }
1072
1073            /**
1074             * <p>
1075             * Tests if some key maps into the specified value in this hashtable.
1076             * This operation is more expensive than the <code>containsKey</code>
1077             * method.
1078             * </p>
1079             * <p>
1080             * Note that this method is identical in functionality to containsValue,
1081             * (which is part of the Map interface in the collections framework).
1082             * </p>
1083             *
1084             * @param value a value to search for.
1085             * @return <code>true</code> if and only if some key maps to the
1086             * <code>value</code> argument in this hashtable as determined
1087             * by the <tt>equals</tt> method; <code>false</code>
1088             * otherwise.
1089             * @throws NullPointerException if the value is <code>null</code>.
1090             * @see #containsKey(int)
1091             * @see #containsValue(Object)
1092             * @see java.util.Map
1093             */

1094            public boolean contains(Object JavaDoc value)
1095            {
1096                if (value == null)
1097                {
1098                    throw new NullPointerException JavaDoc();
1099                }
1100
1101                Entry tab[] = table;
1102                for (int i = tab.length; i-- > 0;)
1103                {
1104                    for (Entry e = tab[i]; e != null; e = e.next)
1105                    {
1106                        if (e.value.equals(value))
1107                        {
1108                            return true;
1109                        }
1110                    }
1111                }
1112                return false;
1113            }
1114
1115            /**
1116             * <p>
1117             * Returns <code>true</code> if this HashMap maps one or more keys to
1118             * this value.
1119             * </p>
1120             * <p>
1121             * Note that this method is identical in functionality to contains (which
1122             * predates the Map interface).
1123             * </p>
1124             *
1125             * @param value value whose presence in this HashMap is to be tested.
1126             * @return boolean <code>true</code> if the value is contained
1127             * @see java.util.Map
1128             * @since JDK1.2
1129             */

1130            public boolean containsValue(Object JavaDoc value)
1131            {
1132                return contains(value);
1133            }
1134
1135            /**
1136             * <p>
1137             * Tests if the specified object is a key in this hashtable.
1138             * </p>
1139             *
1140             * @param key possible key.
1141             * @return <code>true</code> if and only if the specified object is a
1142             * key in this hashtable, as determined by the <tt>equals</tt>
1143             * method; <code>false</code> otherwise.
1144             * @see #contains(Object)
1145             */

1146            public boolean containsKey(int key)
1147            {
1148                Entry tab[] = table;
1149                int hash = key;
1150                int index = (hash & 0x7FFFFFFF) % tab.length;
1151                for (Entry e = tab[index]; e != null; e = e.next)
1152                {
1153                    if (e.hash == hash)
1154                    {
1155                        return true;
1156                    }
1157                }
1158                return false;
1159            }
1160
1161            /**
1162             * <p>
1163             * Returns the value to which the specified key is mapped in this map.
1164             * </p>
1165             *
1166             * @param key a key in the hashtable.
1167             * @return the value to which the key is mapped in this hashtable;
1168             * <code>null</code> if the key is not mapped to any value in
1169             * this hashtable.
1170             * @see #put(int, Object)
1171             */

1172            public Object JavaDoc get(int key)
1173            {
1174                Entry tab[] = table;
1175                int hash = key;
1176                int index = (hash & 0x7FFFFFFF) % tab.length;
1177                for (Entry e = tab[index]; e != null; e = e.next)
1178                {
1179                    if (e.hash == hash)
1180                    {
1181                        return e.value;
1182                    }
1183                }
1184                return null;
1185            }
1186
1187            /**
1188             * <p>
1189             * Increases the capacity of and internally reorganizes this hashtable,
1190             * in order to accommodate and access its entries more efficiently.
1191             * </p>
1192             * <p>
1193             * This method is called automatically when the number of keys in the
1194             * hashtable exceeds this hashtable's capacity and load factor.
1195             * </p>
1196             */

1197            protected void rehash()
1198            {
1199                int oldCapacity = table.length;
1200                Entry oldMap[] = table;
1201
1202                int newCapacity = oldCapacity * 2 + 1;
1203                Entry newMap[] = new Entry[newCapacity];
1204
1205                threshold = (int)(newCapacity * loadFactor);
1206                table = newMap;
1207
1208                for (int i = oldCapacity; i-- > 0;)
1209                {
1210                    for (Entry old = oldMap[i]; old != null;)
1211                    {
1212                        Entry e = old;
1213                        old = old.next;
1214
1215                        int index = (e.hash & 0x7FFFFFFF) % newCapacity;
1216                        e.next = newMap[index];
1217                        newMap[index] = e;
1218                    }
1219                }
1220            }
1221
1222            /**
1223             * <p>
1224             * Maps the specified <code>key</code> to the specified
1225             * <code>value</code> in this hashtable. The key cannot be
1226             * <code>null</code>.
1227             * </p>
1228             * <p>
1229             * The value can be retrieved by calling the <code>get</code> method
1230             * with a key that is equal to the original key.
1231             * </p>
1232             *
1233             * @param key the hashtable key.
1234             * @param value the value.
1235             * @return the previous value of the specified key in this hashtable, or
1236             * <code>null</code> if it did not have one.
1237             * @throws NullPointerException if the key is <code>null</code>.
1238             * @see #get(int)
1239             */

1240            public Object JavaDoc put(int key, Object JavaDoc value)
1241            {
1242                // Makes sure the key is not already in the hashtable.
1243
Entry tab[] = table;
1244                int hash = key;
1245                int index = (hash & 0x7FFFFFFF) % tab.length;
1246                for (Entry e = tab[index]; e != null; e = e.next)
1247                {
1248                    if (e.hash == hash)
1249                    {
1250                        Object JavaDoc old = e.value;
1251                        e.value = value;
1252                        return old;
1253                    }
1254                }
1255
1256                if (count >= threshold)
1257                {
1258                    // Rehash the table if the threshold is exceeded
1259
rehash();
1260
1261                    tab = table;
1262                    index = (hash & 0x7FFFFFFF) % tab.length;
1263                }
1264
1265                // Creates the new entry.
1266
Entry e = new Entry(hash, key, value, tab[index]);
1267                tab[index] = e;
1268                count++;
1269                return null;
1270            }
1271
1272            /**
1273             * <p>
1274             * Removes the key (and its corresponding value) from this hashtable.
1275             * </p>
1276             * <p>
1277             * This method does nothing if the key is not present in the hashtable.
1278             * </p>
1279             *
1280             * @param key the key that needs to be removed.
1281             * @return the value to which the key had been mapped in this hashtable,
1282             * or <code>null</code> if the key did not have a mapping.
1283             */

1284            public Object JavaDoc remove(int key)
1285            {
1286                Entry tab[] = table;
1287                int hash = key;
1288                int index = (hash & 0x7FFFFFFF) % tab.length;
1289                for (Entry e = tab[index], prev = null; e != null; prev = e, e = e.next)
1290                {
1291                    if (e.hash == hash)
1292                    {
1293                        if (prev != null)
1294                        {
1295                            prev.next = e.next;
1296                        }
1297                        else
1298                        {
1299                            tab[index] = e.next;
1300                        }
1301                        count--;
1302                        Object JavaDoc oldValue = e.value;
1303                        e.value = null;
1304                        return oldValue;
1305                    }
1306                }
1307                return null;
1308            }
1309
1310            /**
1311             * <p>Clears this hashtable so that it contains no keys.</p>
1312             */

1313            public synchronized void clear()
1314            {
1315                Entry tab[] = table;
1316                for (int index = tab.length; --index >= 0;)
1317                {
1318                    tab[index] = null;
1319                }
1320                count = 0;
1321            }
1322
1323        }
1324
1325    }
1326}
1327
Popular Tags