Codebase list libgettext-commons-java / debian/0.9.6-1
Merge commit 'upstream/0.9.6' Giovanni Mascellani 14 years ago
34 changed file(s) with 3027 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 2008-04-12 Felix Berger <felixberger@beldesign.de>
1
2 * src/java/org/xnap/commons/i18n/I18nCache.java: Fixed
3 synchronization and improved visitor traversal by moving it out of
4 the synchronized block.
5
6 2008-04-10 Felix Berger <felixberger@beldesign.de>
7
8 * src/java/org/xnap/commons/i18n/I18n.java: Made thread-safe.
9
10 * src/java/org/xnap/commons/i18n/I18nCache.java: Made thread-safe.
11
12 2006-08-22 Steffen Pingel <steffen.pingel@googlemail.com>
13
14 * Gettext Commons 0.9.1 released
15
16 2007-08-22 Steffen Pingel <steffen.pingel@googlemail.com>
17
18 * src/java/org/xnap/commons/i18n/I18nFactory.java: Modified lookup strategy to
19 only check for property files when no bundle name is provided.
20
21 2007-08-21 Steffen Pingel <steffen.pingel@googlemail.com>
22
23 * src/java/org/xnap/commons/i18n/I18nManager.java: Do not set default locale anymore.
24
25 * src/java/org/xnap/commons/i18n/EmptyResourceBundle.java: Added locale parameter.
26
27 * src/java/org/xnap/commons/i18n/I18n.java: Store only a single bundle and also store locale.
28
29 * src/java/org/xnap/commons/i18n/I18nFactory.java: Added NO_CACHE flag, extracted caching to
30 I18nCache.
31
32 * src/java/org/xnap/commons/i18n/I18nCache.java: Cache by package and locale.
33
34 2007-08-06 Steffen Pingel <steffen.pingel@googlemail.com>
35
36 * src/java/org/xnap/commons/i18n/I18nFactory.java: Added private
37 constructor.
38
39 * src/java/org/xnap/commons/i18n/I18nFactory.java: Added getI18n()
40 method that accepts configuration flags. If I18nFactory.FALLBACK is
41 passed the lookup will fall-back to a default resource bundle
42 instead of throwing an exception (#3). Lookup of the basename in
43 properties can now be omitted when I18nFactory.READ_PROPERTIES
44 is not passed as a configuration flag.
45
46 2006-01-05 Steffen Pingel <squig@users.sourceforge.net>
47
48 * Gettext Commons 0.9 released
49
50 2006-01-03 Steffen Pingel <squig@users.sourceforge.net>
51
52 * src/java/org/xnap/commons/i18n/I18nManager.java: Moved
53 non-factory related methods to this class.
54
55 * src/java/org/xnap/commons/i18n/I18nFactory.java: Implemented
56 weak listener.
57
58 2005-12-24 Steffen Pingel <squig@users.sourceforge.net>
59
60 * src/java/org/xnap/commons/i18n/: Created project: Moved i18n
61 package from XNap Commons to this project.
0 GNU LESSER GENERAL PUBLIC LICENSE
1 Version 2.1, February 1999
2
3 Copyright (C) 1991, 1999 Free Software Foundation, Inc.
4 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
5 Everyone is permitted to copy and distribute verbatim copies
6 of this license document, but changing it is not allowed.
7
8 [This is the first released version of the Lesser GPL. It also counts
9 as the successor of the GNU Library Public License, version 2, hence
10 the version number 2.1.]
11
12 Preamble
13
14 The licenses for most software are designed to take away your
15 freedom to share and change it. By contrast, the GNU General Public
16 Licenses are intended to guarantee your freedom to share and change
17 free software--to make sure the software is free for all its users.
18
19 This license, the Lesser General Public License, applies to some
20 specially designated software packages--typically libraries--of the
21 Free Software Foundation and other authors who decide to use it. You
22 can use it too, but we suggest you first think carefully about whether
23 this license or the ordinary General Public License is the better
24 strategy to use in any particular case, based on the explanations below.
25
26 When we speak of free software, we are referring to freedom of use,
27 not price. Our General Public Licenses are designed to make sure that
28 you have the freedom to distribute copies of free software (and charge
29 for this service if you wish); that you receive source code or can get
30 it if you want it; that you can change the software and use pieces of
31 it in new free programs; and that you are informed that you can do
32 these things.
33
34 To protect your rights, we need to make restrictions that forbid
35 distributors to deny you these rights or to ask you to surrender these
36 rights. These restrictions translate to certain responsibilities for
37 you if you distribute copies of the library or if you modify it.
38
39 For example, if you distribute copies of the library, whether gratis
40 or for a fee, you must give the recipients all the rights that we gave
41 you. You must make sure that they, too, receive or can get the source
42 code. If you link other code with the library, you must provide
43 complete object files to the recipients, so that they can relink them
44 with the library after making changes to the library and recompiling
45 it. And you must show them these terms so they know their rights.
46
47 We protect your rights with a two-step method: (1) we copyright the
48 library, and (2) we offer you this license, which gives you legal
49 permission to copy, distribute and/or modify the library.
50
51 To protect each distributor, we want to make it very clear that
52 there is no warranty for the free library. Also, if the library is
53 modified by someone else and passed on, the recipients should know
54 that what they have is not the original version, so that the original
55 author's reputation will not be affected by problems that might be
56 introduced by others.
57
58 Finally, software patents pose a constant threat to the existence of
59 any free program. We wish to make sure that a company cannot
60 effectively restrict the users of a free program by obtaining a
61 restrictive license from a patent holder. Therefore, we insist that
62 any patent license obtained for a version of the library must be
63 consistent with the full freedom of use specified in this license.
64
65 Most GNU software, including some libraries, is covered by the
66 ordinary GNU General Public License. This license, the GNU Lesser
67 General Public License, applies to certain designated libraries, and
68 is quite different from the ordinary General Public License. We use
69 this license for certain libraries in order to permit linking those
70 libraries into non-free programs.
71
72 When a program is linked with a library, whether statically or using
73 a shared library, the combination of the two is legally speaking a
74 combined work, a derivative of the original library. The ordinary
75 General Public License therefore permits such linking only if the
76 entire combination fits its criteria of freedom. The Lesser General
77 Public License permits more lax criteria for linking other code with
78 the library.
79
80 We call this license the "Lesser" General Public License because it
81 does Less to protect the user's freedom than the ordinary General
82 Public License. It also provides other free software developers Less
83 of an advantage over competing non-free programs. These disadvantages
84 are the reason we use the ordinary General Public License for many
85 libraries. However, the Lesser license provides advantages in certain
86 special circumstances.
87
88 For example, on rare occasions, there may be a special need to
89 encourage the widest possible use of a certain library, so that it becomes
90 a de-facto standard. To achieve this, non-free programs must be
91 allowed to use the library. A more frequent case is that a free
92 library does the same job as widely used non-free libraries. In this
93 case, there is little to gain by limiting the free library to free
94 software only, so we use the Lesser General Public License.
95
96 In other cases, permission to use a particular library in non-free
97 programs enables a greater number of people to use a large body of
98 free software. For example, permission to use the GNU C Library in
99 non-free programs enables many more people to use the whole GNU
100 operating system, as well as its variant, the GNU/Linux operating
101 system.
102
103 Although the Lesser General Public License is Less protective of the
104 users' freedom, it does ensure that the user of a program that is
105 linked with the Library has the freedom and the wherewithal to run
106 that program using a modified version of the Library.
107
108 The precise terms and conditions for copying, distribution and
109 modification follow. Pay close attention to the difference between a
110 "work based on the library" and a "work that uses the library". The
111 former contains code derived from the library, whereas the latter must
112 be combined with the library in order to run.
113
114 GNU LESSER GENERAL PUBLIC LICENSE
115 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
116
117 0. This License Agreement applies to any software library or other
118 program which contains a notice placed by the copyright holder or
119 other authorized party saying it may be distributed under the terms of
120 this Lesser General Public License (also called "this License").
121 Each licensee is addressed as "you".
122
123 A "library" means a collection of software functions and/or data
124 prepared so as to be conveniently linked with application programs
125 (which use some of those functions and data) to form executables.
126
127 The "Library", below, refers to any such software library or work
128 which has been distributed under these terms. A "work based on the
129 Library" means either the Library or any derivative work under
130 copyright law: that is to say, a work containing the Library or a
131 portion of it, either verbatim or with modifications and/or translated
132 straightforwardly into another language. (Hereinafter, translation is
133 included without limitation in the term "modification".)
134
135 "Source code" for a work means the preferred form of the work for
136 making modifications to it. For a library, complete source code means
137 all the source code for all modules it contains, plus any associated
138 interface definition files, plus the scripts used to control compilation
139 and installation of the library.
140
141 Activities other than copying, distribution and modification are not
142 covered by this License; they are outside its scope. The act of
143 running a program using the Library is not restricted, and output from
144 such a program is covered only if its contents constitute a work based
145 on the Library (independent of the use of the Library in a tool for
146 writing it). Whether that is true depends on what the Library does
147 and what the program that uses the Library does.
148
149 1. You may copy and distribute verbatim copies of the Library's
150 complete source code as you receive it, in any medium, provided that
151 you conspicuously and appropriately publish on each copy an
152 appropriate copyright notice and disclaimer of warranty; keep intact
153 all the notices that refer to this License and to the absence of any
154 warranty; and distribute a copy of this License along with the
155 Library.
156
157 You may charge a fee for the physical act of transferring a copy,
158 and you may at your option offer warranty protection in exchange for a
159 fee.
160
161 2. You may modify your copy or copies of the Library or any portion
162 of it, thus forming a work based on the Library, and copy and
163 distribute such modifications or work under the terms of Section 1
164 above, provided that you also meet all of these conditions:
165
166 a) The modified work must itself be a software library.
167
168 b) You must cause the files modified to carry prominent notices
169 stating that you changed the files and the date of any change.
170
171 c) You must cause the whole of the work to be licensed at no
172 charge to all third parties under the terms of this License.
173
174 d) If a facility in the modified Library refers to a function or a
175 table of data to be supplied by an application program that uses
176 the facility, other than as an argument passed when the facility
177 is invoked, then you must make a good faith effort to ensure that,
178 in the event an application does not supply such function or
179 table, the facility still operates, and performs whatever part of
180 its purpose remains meaningful.
181
182 (For example, a function in a library to compute square roots has
183 a purpose that is entirely well-defined independent of the
184 application. Therefore, Subsection 2d requires that any
185 application-supplied function or table used by this function must
186 be optional: if the application does not supply it, the square
187 root function must still compute square roots.)
188
189 These requirements apply to the modified work as a whole. If
190 identifiable sections of that work are not derived from the Library,
191 and can be reasonably considered independent and separate works in
192 themselves, then this License, and its terms, do not apply to those
193 sections when you distribute them as separate works. But when you
194 distribute the same sections as part of a whole which is a work based
195 on the Library, the distribution of the whole must be on the terms of
196 this License, whose permissions for other licensees extend to the
197 entire whole, and thus to each and every part regardless of who wrote
198 it.
199
200 Thus, it is not the intent of this section to claim rights or contest
201 your rights to work written entirely by you; rather, the intent is to
202 exercise the right to control the distribution of derivative or
203 collective works based on the Library.
204
205 In addition, mere aggregation of another work not based on the Library
206 with the Library (or with a work based on the Library) on a volume of
207 a storage or distribution medium does not bring the other work under
208 the scope of this License.
209
210 3. You may opt to apply the terms of the ordinary GNU General Public
211 License instead of this License to a given copy of the Library. To do
212 this, you must alter all the notices that refer to this License, so
213 that they refer to the ordinary GNU General Public License, version 2,
214 instead of to this License. (If a newer version than version 2 of the
215 ordinary GNU General Public License has appeared, then you can specify
216 that version instead if you wish.) Do not make any other change in
217 these notices.
218
219 Once this change is made in a given copy, it is irreversible for
220 that copy, so the ordinary GNU General Public License applies to all
221 subsequent copies and derivative works made from that copy.
222
223 This option is useful when you wish to copy part of the code of
224 the Library into a program that is not a library.
225
226 4. You may copy and distribute the Library (or a portion or
227 derivative of it, under Section 2) in object code or executable form
228 under the terms of Sections 1 and 2 above provided that you accompany
229 it with the complete corresponding machine-readable source code, which
230 must be distributed under the terms of Sections 1 and 2 above on a
231 medium customarily used for software interchange.
232
233 If distribution of object code is made by offering access to copy
234 from a designated place, then offering equivalent access to copy the
235 source code from the same place satisfies the requirement to
236 distribute the source code, even though third parties are not
237 compelled to copy the source along with the object code.
238
239 5. A program that contains no derivative of any portion of the
240 Library, but is designed to work with the Library by being compiled or
241 linked with it, is called a "work that uses the Library". Such a
242 work, in isolation, is not a derivative work of the Library, and
243 therefore falls outside the scope of this License.
244
245 However, linking a "work that uses the Library" with the Library
246 creates an executable that is a derivative of the Library (because it
247 contains portions of the Library), rather than a "work that uses the
248 library". The executable is therefore covered by this License.
249 Section 6 states terms for distribution of such executables.
250
251 When a "work that uses the Library" uses material from a header file
252 that is part of the Library, the object code for the work may be a
253 derivative work of the Library even though the source code is not.
254 Whether this is true is especially significant if the work can be
255 linked without the Library, or if the work is itself a library. The
256 threshold for this to be true is not precisely defined by law.
257
258 If such an object file uses only numerical parameters, data
259 structure layouts and accessors, and small macros and small inline
260 functions (ten lines or less in length), then the use of the object
261 file is unrestricted, regardless of whether it is legally a derivative
262 work. (Executables containing this object code plus portions of the
263 Library will still fall under Section 6.)
264
265 Otherwise, if the work is a derivative of the Library, you may
266 distribute the object code for the work under the terms of Section 6.
267 Any executables containing that work also fall under Section 6,
268 whether or not they are linked directly with the Library itself.
269
270 6. As an exception to the Sections above, you may also combine or
271 link a "work that uses the Library" with the Library to produce a
272 work containing portions of the Library, and distribute that work
273 under terms of your choice, provided that the terms permit
274 modification of the work for the customer's own use and reverse
275 engineering for debugging such modifications.
276
277 You must give prominent notice with each copy of the work that the
278 Library is used in it and that the Library and its use are covered by
279 this License. You must supply a copy of this License. If the work
280 during execution displays copyright notices, you must include the
281 copyright notice for the Library among them, as well as a reference
282 directing the user to the copy of this License. Also, you must do one
283 of these things:
284
285 a) Accompany the work with the complete corresponding
286 machine-readable source code for the Library including whatever
287 changes were used in the work (which must be distributed under
288 Sections 1 and 2 above); and, if the work is an executable linked
289 with the Library, with the complete machine-readable "work that
290 uses the Library", as object code and/or source code, so that the
291 user can modify the Library and then relink to produce a modified
292 executable containing the modified Library. (It is understood
293 that the user who changes the contents of definitions files in the
294 Library will not necessarily be able to recompile the application
295 to use the modified definitions.)
296
297 b) Use a suitable shared library mechanism for linking with the
298 Library. A suitable mechanism is one that (1) uses at run time a
299 copy of the library already present on the user's computer system,
300 rather than copying library functions into the executable, and (2)
301 will operate properly with a modified version of the library, if
302 the user installs one, as long as the modified version is
303 interface-compatible with the version that the work was made with.
304
305 c) Accompany the work with a written offer, valid for at
306 least three years, to give the same user the materials
307 specified in Subsection 6a, above, for a charge no more
308 than the cost of performing this distribution.
309
310 d) If distribution of the work is made by offering access to copy
311 from a designated place, offer equivalent access to copy the above
312 specified materials from the same place.
313
314 e) Verify that the user has already received a copy of these
315 materials or that you have already sent this user a copy.
316
317 For an executable, the required form of the "work that uses the
318 Library" must include any data and utility programs needed for
319 reproducing the executable from it. However, as a special exception,
320 the materials to be distributed need not include anything that is
321 normally distributed (in either source or binary form) with the major
322 components (compiler, kernel, and so on) of the operating system on
323 which the executable runs, unless that component itself accompanies
324 the executable.
325
326 It may happen that this requirement contradicts the license
327 restrictions of other proprietary libraries that do not normally
328 accompany the operating system. Such a contradiction means you cannot
329 use both them and the Library together in an executable that you
330 distribute.
331
332 7. You may place library facilities that are a work based on the
333 Library side-by-side in a single library together with other library
334 facilities not covered by this License, and distribute such a combined
335 library, provided that the separate distribution of the work based on
336 the Library and of the other library facilities is otherwise
337 permitted, and provided that you do these two things:
338
339 a) Accompany the combined library with a copy of the same work
340 based on the Library, uncombined with any other library
341 facilities. This must be distributed under the terms of the
342 Sections above.
343
344 b) Give prominent notice with the combined library of the fact
345 that part of it is a work based on the Library, and explaining
346 where to find the accompanying uncombined form of the same work.
347
348 8. You may not copy, modify, sublicense, link with, or distribute
349 the Library except as expressly provided under this License. Any
350 attempt otherwise to copy, modify, sublicense, link with, or
351 distribute the Library is void, and will automatically terminate your
352 rights under this License. However, parties who have received copies,
353 or rights, from you under this License will not have their licenses
354 terminated so long as such parties remain in full compliance.
355
356 9. You are not required to accept this License, since you have not
357 signed it. However, nothing else grants you permission to modify or
358 distribute the Library or its derivative works. These actions are
359 prohibited by law if you do not accept this License. Therefore, by
360 modifying or distributing the Library (or any work based on the
361 Library), you indicate your acceptance of this License to do so, and
362 all its terms and conditions for copying, distributing or modifying
363 the Library or works based on it.
364
365 10. Each time you redistribute the Library (or any work based on the
366 Library), the recipient automatically receives a license from the
367 original licensor to copy, distribute, link with or modify the Library
368 subject to these terms and conditions. You may not impose any further
369 restrictions on the recipients' exercise of the rights granted herein.
370 You are not responsible for enforcing compliance by third parties with
371 this License.
372
373 11. If, as a consequence of a court judgment or allegation of patent
374 infringement or for any other reason (not limited to patent issues),
375 conditions are imposed on you (whether by court order, agreement or
376 otherwise) that contradict the conditions of this License, they do not
377 excuse you from the conditions of this License. If you cannot
378 distribute so as to satisfy simultaneously your obligations under this
379 License and any other pertinent obligations, then as a consequence you
380 may not distribute the Library at all. For example, if a patent
381 license would not permit royalty-free redistribution of the Library by
382 all those who receive copies directly or indirectly through you, then
383 the only way you could satisfy both it and this License would be to
384 refrain entirely from distribution of the Library.
385
386 If any portion of this section is held invalid or unenforceable under any
387 particular circumstance, the balance of the section is intended to apply,
388 and the section as a whole is intended to apply in other circumstances.
389
390 It is not the purpose of this section to induce you to infringe any
391 patents or other property right claims or to contest validity of any
392 such claims; this section has the sole purpose of protecting the
393 integrity of the free software distribution system which is
394 implemented by public license practices. Many people have made
395 generous contributions to the wide range of software distributed
396 through that system in reliance on consistent application of that
397 system; it is up to the author/donor to decide if he or she is willing
398 to distribute software through any other system and a licensee cannot
399 impose that choice.
400
401 This section is intended to make thoroughly clear what is believed to
402 be a consequence of the rest of this License.
403
404 12. If the distribution and/or use of the Library is restricted in
405 certain countries either by patents or by copyrighted interfaces, the
406 original copyright holder who places the Library under this License may add
407 an explicit geographical distribution limitation excluding those countries,
408 so that distribution is permitted only in or among countries not thus
409 excluded. In such case, this License incorporates the limitation as if
410 written in the body of this License.
411
412 13. The Free Software Foundation may publish revised and/or new
413 versions of the Lesser General Public License from time to time.
414 Such new versions will be similar in spirit to the present version,
415 but may differ in detail to address new problems or concerns.
416
417 Each version is given a distinguishing version number. If the Library
418 specifies a version number of this License which applies to it and
419 "any later version", you have the option of following the terms and
420 conditions either of that version or of any later version published by
421 the Free Software Foundation. If the Library does not specify a
422 license version number, you may choose any version ever published by
423 the Free Software Foundation.
424
425 14. If you wish to incorporate parts of the Library into other free
426 programs whose distribution conditions are incompatible with these,
427 write to the author to ask for permission. For software which is
428 copyrighted by the Free Software Foundation, write to the Free
429 Software Foundation; we sometimes make exceptions for this. Our
430 decision will be guided by the two goals of preserving the free status
431 of all derivatives of our free software and of promoting the sharing
432 and reuse of software generally.
433
434 NO WARRANTY
435
436 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
437 WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
438 EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
439 OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
440 KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
441 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
442 PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
443 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
444 THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
445
446 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
447 WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
448 AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
449 FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
450 CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
451 LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
452 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
453 FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
454 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
455 DAMAGES.
456
457 END OF TERMS AND CONDITIONS
458
459 How to Apply These Terms to Your New Libraries
460
461 If you develop a new library, and you want it to be of the greatest
462 possible use to the public, we recommend making it free software that
463 everyone can redistribute and change. You can do so by permitting
464 redistribution under these terms (or, alternatively, under the terms of the
465 ordinary General Public License).
466
467 To apply these terms, attach the following notices to the library. It is
468 safest to attach them to the start of each source file to most effectively
469 convey the exclusion of warranty; and each file should have at least the
470 "copyright" line and a pointer to where the full notice is found.
471
472 <one line to give the library's name and a brief idea of what it does.>
473 Copyright (C) <year> <name of author>
474
475 This library is free software; you can redistribute it and/or
476 modify it under the terms of the GNU Lesser General Public
477 License as published by the Free Software Foundation; either
478 version 2.1 of the License, or (at your option) any later version.
479
480 This library is distributed in the hope that it will be useful,
481 but WITHOUT ANY WARRANTY; without even the implied warranty of
482 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
483 Lesser General Public License for more details.
484
485 You should have received a copy of the GNU Lesser General Public
486 License along with this library; if not, write to the Free Software
487 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
488
489 Also add information on how to contact you by electronic and paper mail.
490
491 You should also get your employer (if you work as a programmer) or your
492 school, if any, to sign a "copyright disclaimer" for the library, if
493 necessary. Here is a sample; alter the names:
494
495 Yoyodyne, Inc., hereby disclaims all copyright interest in the
496 library `Frob' (a library for tweaking knobs) written by James Random Hacker.
497
498 <signature of Ty Coon>, 1 April 1990
499 Ty Coon, President of Vice
500
501 That's all there is to it!
502
503
0 INTRODUCTION
1
2 The Gettext Commons project provides Java classes for
3 internationalization (i18n) through GNU gettext and Java
4 ResourceBundles. This makes it possible to use the original text
5 instead of arbitrary property keys, which is less cumbersome and
6 makes programs easier to read. Gettext supports the easy extraction
7 of user visible strings, marks strings as fuzzy when the original
8 text changes to allow translators to check translations, powerful
9 plural handling, and build process integration through Maven.
10
11 A tutorial that describes how to use the Gettext Commons is available
12 at http://code.google.com/p/gettext-commons/wiki/Tutorial .
13
14
15 REQUIREMENTS
16
17 * Java 1.3 (or higher)
18
19
20 DEVELOPMENT
21
22 Apache Maven 2.0 can be used to build the Gettext Commons.
23
24
25 COPYRIGHT
26
27 XNap Commons is distributed under the terms of the GNU Lesser General
28 Public License, see LICENSE.txt for details. The icons directory
29 contains images from the KDE project, see LICENSE.icons for terms of
30 use.
31
32 Copyright (C) 2005 Felix Berger
33 Copyright (C) 2005 Steffen Pingel
34 Copyright (C) 2005 Tammo van Lessen
35
36 This library is free software; you can redistribute it and/or
37 modify it under the terms of the GNU Lesser General Public
38 License as published by the Free Software Foundation; either
39 version 2.1 of the License, or (at your option) any later version.
40
41 This library is distributed in the hope that it will be useful,
42 but WITHOUT ANY WARRANTY; without even the implied warranty of
43 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
44 Lesser General Public License for more details.
0 <project xmlns="http://maven.apache.org/POM/4.0.0"
1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <groupId>org.xnap.commons</groupId>
5 <artifactId>gettext-commons</artifactId>
6 <packaging>jar</packaging>
7 <version>0.9.6</version>
8 <name>Gettext Commons</name>
9 <url>http://code.google.com/p/gettext-commons/</url>
10 <description>
11 A library that supports gettext-based internationalization
12 (i18n) of Java applications.
13 </description>
14 <developers>
15 <developer>
16 <name>Felix Berger</name>
17 <id>bergerfx</id>
18 <roles>
19 <role>Developer</role>
20 </roles>
21 <url>http://www.felix.beldesign.de/</url>
22 </developer>
23 <developer>
24 <name>Tammo van Lessen</name>
25 <id>tvanlessen</id>
26 <roles>
27 <role>Developer</role>
28 </roles>
29 <url>http://taval.de/</url>
30 </developer>
31 <developer>
32 <name>Steffen Pingel</name>
33 <id>steffen.pingel</id>
34 <roles>
35 <role>Project Manager</role>
36 <role>Developer</role>
37 </roles>
38 <url>http://steffenpingel.de</url>
39 </developer>
40 </developers>
41 <dependencies>
42 <dependency>
43 <groupId>junit</groupId>
44 <artifactId>junit</artifactId>
45 <version>3.8.1</version>
46 <scope>test</scope>
47 </dependency>
48 </dependencies>
49 <scm>
50 <connection>
51 scm:svn:http://gettext-commons.googlecode.com/svn/trunk
52 </connection>
53 <developerConnection>
54 scm:cvs:https://gettext-commons.googlecode.com/svn/trunk
55 </developerConnection>
56 <url>http://gettext-commons.googlecode.com/svn/trunk</url>
57 </scm>
58 <build>
59 <sourceDirectory>src/java</sourceDirectory>
60 <testSourceDirectory>src/test</testSourceDirectory>
61 <resources>
62 <resource>
63 <directory>src/conf</directory>
64 </resource>
65 </resources>
66 <testResources>
67 <testResource>
68 <directory>src/test-resources</directory>
69 </testResource>
70 </testResources>
71 <pluginManagement>
72 <plugins>
73 <plugin>
74 <groupId>org.apache.maven.plugins</groupId>
75 <artifactId>maven-compiler-plugin</artifactId>
76 <configuration>
77 <source>1.4</source>
78 <target>1.4</target>
79 </configuration>
80 </plugin>
81 <plugin>
82 <groupId>org.apache.maven.plugins</groupId>
83 <artifactId>maven-eclipse-plugin</artifactId>
84 <configuration>
85 <projectnatures>
86 <java.lang.String>
87 org.eclipse.jdt.core.javanature
88 </java.lang.String>
89 </projectnatures>
90 <buildcommands>
91 <java.lang.String>
92 org.eclipse.jdt.core.javabuilder
93 </java.lang.String>
94 </buildcommands>
95 </configuration>
96 </plugin>
97 </plugins>
98 </pluginManagement>
99 <plugins>
100 <plugin>
101 <groupId>org.apache.maven.plugins</groupId>
102 <artifactId>maven-surefire-plugin</artifactId>
103 <configuration>
104 <testFailureIgnore>true</testFailureIgnore>
105 </configuration>
106 </plugin>
107 <plugin>
108 <artifactId>maven-assembly-plugin</artifactId>
109 <configuration>
110 <descriptors>
111 <descriptor>src/assembly/bin.xml</descriptor>
112 <descriptor>src/assembly/src.xml</descriptor>
113 </descriptors>
114 </configuration>
115 <executions>
116 <execution>
117 <id>make-assembly</id> <!-- this is used for inheritance merges -->
118 <phase>package</phase> <!-- append to the packaging phase. -->
119 <goals>
120 <goal>attached</goal> <!-- goals == mojos -->
121 </goals>
122 </execution>
123 </executions>
124 </plugin>
125
126 </plugins>
127 </build>
128 <distributionManagement>
129 <site>
130 <id>xnap-commons</id>
131 <name>XNap Commons Site</name>
132 <url>
133 scp://shell.sf.net//home/groups/x/xn/xnap-commons/htdocs/gettext-commons/
134 </url>
135 </site>
136 <repository>
137 <id>xnap-commons</id>
138 <name>XNap Commons Repository</name>
139 <url>
140 scp://shell.sf.net//home/groups/x/xn/xnap-commons/htdocs/repository
141 </url>
142 </repository>
143 </distributionManagement>
144 <reporting>
145 <plugins>
146 <!--
147 <plugin>
148 <groupId>org.codehaus.mojo</groupId>
149 <artifactId>changes-maven-plugin</artifactId>
150 <configuration>
151 <xmlPath>xdocs/changes.xml</xmlPath>
152 </configuration>
153 </plugin>
154 -->
155 <plugin>
156 <groupId>org.xnap.commons</groupId>
157 <artifactId>maven-gettext-plugin</artifactId>
158 <configuration>
159 <poDirectory>po</poDirectory>
160 <targetBundle>
161 org.xnap.commons.i18n.Messages
162 </targetBundle>
163 <poDirectory>${basedir}/po</poDirectory>
164 </configuration>
165 </plugin>
166 </plugins>
167 </reporting>
168 </project>
0 <assembly>
1 <id>bin</id>
2 <formats>
3 <format>tar.gz</format>
4 <format>tar.bz2</format>
5 <format>zip</format>
6 </formats>
7 <fileSets>
8 <fileSet>
9 <includes>
10 <include>README*</include>
11 <include>LICENSE*</include>
12 <include>NOTICE*</include>
13 <include>ChangeLog*</include>
14 </includes>
15 </fileSet>
16 <fileSet>
17 <directory>target</directory>
18 <outputDirectory></outputDirectory>
19 <includes>
20 <include>*.jar</include>
21 </includes>
22 </fileSet>
23 </fileSets>
24 </assembly>
0 <assembly>
1 <id>src</id>
2 <formats>
3 <format>tar.gz</format>
4 <format>tar.bz2</format>
5 <format>zip</format>
6 </formats>
7 <fileSets>
8 <fileSet>
9 <includes>
10 <include>README*</include>
11 <include>LICENSE*</include>
12 <include>NOTICE*</include>
13 <include>ChangeLog*</include>
14 <include>pom.xml</include>
15 </includes>
16 <useDefaultExcludes>true</useDefaultExcludes>
17 </fileSet>
18 <fileSet>
19 <directory>src</directory>
20 <useDefaultExcludes>true</useDefaultExcludes>
21 </fileSet>
22 </fileSets>
23 </assembly>
0 import java.util.Locale;
1 import org.xnap.commons.i18n.I18n;
2 import org.xnap.commons.i18n.I18nFactory;
3
4 /**
5 * This example class illustrates how the methods provided by {@link i18n}
6 * can be used to localize text messages.
7 *
8 * Nota bene: Contrary to this example changing the resources during
9 * run-time is usually not a good idea, since most strings are saved in the
10 * swing components and not reread from resource bundles.
11 *
12 * @author Felix Berger
13 */
14 public class I18nExample
15 {
16 public static void main(String[] args)
17 {
18 I18n i18n = I18nFactory.getI18n(I18nExample.class, "Messages");
19 /*
20 * We do two runs, the first with the orginal locale the second one
21 * with the German locale, to see which messages are translated and
22 * how.
23 */
24 for (int i = 0; i < 2; i++) {
25
26 if (i == 0) {
27 print("First run");
28
29 }
30 else {
31 print("Second run");
32 i18n.setLocale(Locale.GERMAN);
33 }
34
35 /*
36 * This is the method you will be using most of the time.
37 */
38 print(i18n.tr("This text is marked for translation and is translated"));
39
40 /*
41 * This method marks the text for translation, but doesn't
42 * translate. This can be used for keys which should be stored
43 * untranslated but should be translated in the user interface.
44 */
45 String mark = i18n.marktr("This text is marked for translation but not translated");
46
47 /*
48 * See in the second run, it's never translated.
49 */
50 print(mark);
51
52 /*
53 * Now you can use the text in a variable and it is correctly
54 * translated.
55 */
56 print(i18n.tr(mark));
57
58 /*
59 * A convenience wrapper for MessageFormat.format(String, Object[]).
60 */
61 print(i18n.tr("Four: {0}", new Integer(4)));
62
63 /*
64 * This method disambiguates a word which has to be translated
65 * differently depending on how it is used. In our example the
66 * word "chat" is translated differently to German when it is
67 * used as a noun and as a verb.
68 */
69 print(i18n.trc("chat (verb)", "chat"));
70
71 print(i18n.trc("chat (noun)", "chat"));
72
73 /*
74 * I18n.trn handles plurals. The third parameter contains the number
75 * of objects to decide which plural form to use.
76 */
77 print(i18n.trn("{0} file is open", "{0} files are open", 1, new Integer(1)));
78
79 print(i18n.trn("{0} file is open", "{0} files are open", 2, new Integer(2)));
80 }
81 }
82
83 private static void print(String text)
84 {
85 System.out.println(text);
86 }
87 }
0 # SOME DESCRIPTIVE TITLE.
1 # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
2 # This file is distributed under the same license as the PACKAGE package.
3 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
4 #
5 #, fuzzy
6 !=Project-Id-Version\: PACKAGE VERSION\nReport-Msgid-Bugs-To\: \nPOT-Creation-Date\: 2004-10-17 19\:24+0200\nPO-Revision-Date\: 2004-10-17 19\:28+0200\nLast-Translator\: FULL NAME <EMAIL@ADDRESS>\nLanguage-Team\: LANGUAGE <LL@li.org>\nMIME-Version\: 1.0\nContent-Type\: text/plain; charset\=UTF-8\nContent-Transfer-Encoding\: 8bit\n
7
8 #: I18nExample.java:21
9 This\ text\ is\ marked\ for\ translation\ and\ is\ translated=Dieser Text ist f\u00fcr die \u00dcbersetzung markiert und wird auch \u00fcbersetzt
10
11 #: I18nExample.java:23
12 This\ text\ is\ tranlated\ and\ padded=Dieser Text wird \u00fcbersetzt und am Rand mit Leerzeichen aufgef\u00fcllt
13
14 #: I18nExample.java:25
15 This\ text\ is\ marked\ for\ translation\ but\ not\ translated=Dieser Text ist f\u00fcr die \u00dcbersetzung markiert wird aber nicht \u00fcbersetzt
16
17 #: I18nExample.java:27
18 #, java-format
19 This\ is\ the\ {0}.\ text\ to\ be\ translated=Dies ist der {0}. Text der \u00fcbersetzt wird
20
21 #: I18nExample.java:29
22 chat\ (verb)=Chatten
23
24 #: I18nExample.java:31
25 chat\ (noun)=Chat
0 # SOME DESCRIPTIVE TITLE.
1 # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
2 # This file is distributed under the same license as the PACKAGE package.
3 # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
4 #
5 #, fuzzy
6 !=Project-Id-Version\: PACKAGE VERSION\nReport-Msgid-Bugs-To\: \nPOT-Creation-Date\: 2004-10-17 19\:24+0200\nPO-Revision-Date\: YEAR-MO-DA HO\:MI+ZONE\nLast-Translator\: FULL NAME <EMAIL@ADDRESS>\nLanguage-Team\: LANGUAGE <LL@li.org>\nMIME-Version\: 1.0\nContent-Type\: text/plain; charset\=UTF-8\nContent-Transfer-Encoding\: 8bit\n
7
8 #: I18nExample.java:21
9 !This\ text\ is\ marked\ for\ translation\ and\ is\ translated=
10
11 #: I18nExample.java:23
12 !This\ text\ is\ tranlated\ and\ padded=
13
14 #: I18nExample.java:25
15 !This\ text\ is\ marked\ for\ translation\ but\ not\ translated=
16
17 #: I18nExample.java:27
18 #, java-format
19 !This\ is\ the\ {0}.\ text\ to\ be\ translated=
20
21 #: I18nExample.java:29
22 !chat\ (verb)=
23
24 #: I18nExample.java:31
25 !chat\ (noun)=
0 package org.xnap.commons.i18n;
1
2 import java.util.Enumeration;
3 import java.util.Locale;
4 import java.util.ResourceBundle;
5
6 /**
7 * A <code>ResourceBundle</code> that returns the key as a value.
8 *
9 * FIXME needs to implement proper plural handling
10 * FIXME the bundle needs to have a valid locale for proper sourceCodeLocale handling
11 */
12 class EmptyResourceBundle extends ResourceBundle
13 {
14 private Locale locale;
15
16 public EmptyResourceBundle(Locale locale)
17 {
18 this.locale = locale;
19 }
20
21 /**
22 * Returns the key as value.
23 */
24 protected Object handleGetObject(String key)
25 {
26 return key;
27 }
28
29 public Enumeration getKeys()
30 {
31 return new EmptyStringEnumeration();
32 }
33
34 public Locale getLocale()
35 {
36 return locale;
37 }
38
39 private static class EmptyStringEnumeration implements Enumeration
40 {
41
42 public boolean hasMoreElements()
43 {
44 return false;
45 }
46
47 public Object nextElement()
48 {
49 throw new IllegalStateException("nextElement must not be " +
50 "called on empty enumeration");
51 }
52
53 }
54
55 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Felix Berger
4 * Copyright (C) 2005 Steffen Pingel
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20 package org.xnap.commons.i18n;
21
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Modifier;
24 import java.text.MessageFormat;
25 import java.util.Locale;
26 import java.util.MissingResourceException;
27 import java.util.ResourceBundle;
28
29 /**
30 * Provides methods for internationalization.
31 * <p>
32 * To learn how message strings wrapped in one of the <code>tr*()</code>
33 * methods can be extracted and localized, see <a
34 * href="http://code.google.com/p/gettext-commons/wiki/Tutorial">this tutorial</a>.
35 *
36 * @author Steffen Pingel
37 * @author Felix Berger
38 * @author Tammo van Lessen
39 * @since 0.9
40 */
41 public class I18n {
42
43 private static final String CONTEXT_GLUE = "\u0004";
44
45 /**
46 * Reference to the current localization bundles.
47 */
48 private volatile ResourceBundle bundle;
49
50 /**
51 * The locale of the strings used in the source code.
52 *
53 * @see #trc(String, String)
54 */
55 private volatile Locale sourceCodeLocale = Locale.ENGLISH;
56
57 private String baseName;
58
59 private ClassLoader loader;
60
61 private volatile Locale locale;
62
63 /**
64 * Constructs an I18n object for a resource bundle.
65 *
66 * @param bundle
67 * must not be <code>null</code>
68 * @throws NullPointerException
69 * if <code>bundle</code> is null
70 * @since 0.9
71 */
72 public I18n(ResourceBundle bundle)
73 {
74 setResources(bundle);
75 }
76
77 /**
78 * Constructs an I18n object by calling {@link #setResources(String, Locale,
79 * ClassLoader)}.
80 *
81 * @throws MissingResourceException
82 * if the resource bundle could not be loaded
83 * @throws NullPointerException
84 * if one of the arguments is <code>null</code>
85 * @since 0.9
86 */
87 public I18n(String baseName, Locale locale, ClassLoader loader)
88 {
89 setResources(baseName, locale, loader);
90 }
91
92 /**
93 * Returns the current resource bundle.
94 *
95 * @since 0.9
96 */
97 public ResourceBundle getResources()
98 {
99 return bundle;
100 }
101
102 /**
103 * Returns the locale this instance was created with. This can be different
104 * from the locale of the resource bundle returned by
105 * {@link #getResources()}.
106 *
107 * @return the locale or null, if this instance was directly created from a
108 * resource bundle
109 * @since 0.9
110 */
111 public Locale getLocale()
112 {
113 return locale;
114 }
115
116 /**
117 * Sets a resource bundle to be used for message translations.
118 * <p>
119 * If this is called, the possibly previously specified class loader and
120 * baseName are invalidated, since the bundle might be from a different
121 * context. Subsequent calls to {@link #setLocale(Locale)} won't have any
122 * effect.
123 *
124 * @since 0.9
125 */
126 public synchronized void setResources(ResourceBundle bundle)
127 {
128 if (bundle == null) {
129 throw new NullPointerException();
130 }
131 this.bundle = bundle;
132 this.baseName = null;
133 this.locale = bundle.getLocale();
134 this.loader = null;
135 }
136
137 /**
138 * Tries to load a resource bundle using {@link
139 * ResourceBundle#getBundle(java.lang.String, java.util.Locale,
140 * java.lang.ClassLoader)}.
141 *
142 * @throws MissingResourceException
143 * if the bundle could not be loaded
144 * @throws NullPointerException
145 * if one of the arguments is <code>null</code>
146 * @since 0.9
147 */
148 public synchronized void setResources(String baseName, Locale locale, ClassLoader loader)
149 {
150 this.bundle = ResourceBundle.getBundle(baseName, locale, loader);
151 this.baseName = baseName;
152 this.locale = locale;
153 this.loader = loader;
154 }
155
156 /**
157 * Marks <code>text</code> to be translated, but doesn't return the
158 * translation but <code>text</code> itself.
159 *
160 * @since 0.9
161 */
162 public static final String marktr(String text)
163 {
164 return text;
165 }
166
167 /**
168 * Tries to load a resource bundle for the locale.
169 * <p>
170 * The resource bundle is then used for message translations. Note, you have
171 * to retrieve all messages anew after a locale change in order for them to
172 * be translated to the language specified by the new locale.
173 * <p>
174 *
175 * @return false if there is not enough information for loading a new
176 * resource bundle, see {@link #setResources(ResourceBundle)}.
177 * @throws MissingResourceException
178 * if the resource bundle for <code>locale</code> could not be
179 * found
180 * @throws NullPointerException
181 * if <code>locale</code> is null
182 * @since 0.9
183 */
184 public synchronized boolean setLocale(Locale locale)
185 {
186 if (baseName != null && loader != null) {
187 setResources(baseName, locale, loader);
188 return true;
189 }
190 else {
191 this.locale = locale;
192 }
193 return false;
194 }
195
196 /**
197 * Sets the locale of the text in the source code.
198 * <p>
199 * Only languages that have one singular and one plural form can be used as
200 * source code locales, since {@link #trn(String, String, long)} takes
201 * exactly these two forms as parameters.
202 *
203 * @param locale
204 * the locale
205 * @throws NullPointerException
206 * if <code>locale</code> is <code>null</code>
207 * @see #trc(String, String)
208 * @since 0.9
209 */
210 public void setSourceCodeLocale(Locale locale)
211 {
212 if (locale == null) {
213 throw new NullPointerException("locale must not be null");
214 }
215 sourceCodeLocale = locale;
216 }
217
218 /**
219 * Returns <code>text</code> translated into the currently selected
220 * language. Every user-visible string in the program must be wrapped into
221 * this function.
222 *
223 * @param text
224 * text to translate
225 * @return the translation
226 * @since 0.9
227 */
228 public final String tr(String text)
229 {
230 try {
231 return bundle.getString(text);
232 }
233 catch (MissingResourceException e) {
234 return text;
235 }
236 }
237
238 /**
239 * Returns <code>text</code> translated into the currently selected
240 * language.
241 * <p>
242 * Occurrences of {number} placeholders in text are replaced by
243 * <code>objects</code>.
244 * <p>
245 * Invokes
246 * {@link MessageFormat#format(java.lang.String, java.lang.Object[])}.
247 *
248 * @param text
249 * text to translate
250 * @param objects
251 * arguments to <code>MessageFormat.format()</code>
252 * @return the translated text
253 * @since 0.9
254 */
255 public final String tr(String text, Object[] objects)
256 {
257 return MessageFormat.format(tr(text), objects);
258 }
259
260 /**
261 * Convenience method that invokes {@link #tr(String, Object[])}.
262 *
263 * @since 0.9
264 */
265 public final String tr(String text, Object o1)
266 {
267 return tr(text, new Object[]{ o1 });
268 }
269
270 /**
271 * Convenience method that invokes {@link #tr(String, Object[])}.
272 *
273 * @since 0.9
274 */
275 public final String tr(String text, Object o1, Object o2)
276 {
277 return tr(text, new Object[]{ o1, o2 });
278 }
279
280 /**
281 * Convenience method that invokes {@link #tr(String, Object[])}.
282 *
283 * @since 0.9
284 */
285 public final String tr(String text, Object o1, Object o2, Object o3)
286 {
287 return tr(text, new Object[]{ o1, o2, o3 });
288 }
289
290 /**
291 * Convenience method that invokes {@link #tr(String, Object[])}.
292 *
293 * @since 0.9
294 */
295 public final String tr(String text, Object o1, Object o2, Object o3, Object o4)
296 {
297 return tr(text, new Object[]{ o1, o2, o3, o4 });
298 }
299
300 /**
301 * Returns the plural form for <code>n</code> of the translation of
302 * <code>text</code>.
303 *
304 * @param text
305 * the key string to be translated.
306 * @param pluralText
307 * the plural form of <code>text</code>.
308 * @param n
309 * value that determines the plural form
310 * @return the translated text
311 * @since 0.9
312 */
313 public final String trn(String text, String pluralText, long n)
314 {
315 try {
316 return trnInternal(bundle, text, pluralText, n);
317 }
318 catch (MissingResourceException e) {
319 return (n == 1) ? text : pluralText;
320 }
321 }
322
323 /**
324 * Returns the plural form for <code>n</code> of the translation of
325 * <code>text</code>.
326 *
327 * @param text
328 * the key string to be translated.
329 * @param pluralText
330 * the plural form of <code>text</code>.
331 * @param n
332 * value that determines the plural form
333 * @param objects
334 * object args to be formatted and substituted.
335 * @return the translated text
336 * @since 0.9
337 */
338 public final String trn(String text, String pluralText, long n, Object[] objects)
339 {
340 return MessageFormat.format(trn(text, pluralText, n), objects);
341 }
342
343 /**
344 * Overloaded method that invokes
345 * {@link #trn(String, String, long, Object[])} passing <code>Object</code>
346 * arguments as an array.
347 *
348 * @since 0.9
349 */
350 public final String trn(String text, String pluralText, long n, Object o1)
351 {
352 return trn(text, pluralText, n, new Object[]{ o1 });
353 }
354
355 /**
356 * Overloaded method that invokes
357 * {@link #trn(String, String, long, Object[])} passing <code>Object</code>
358 * arguments as an array.
359 *
360 * @since 0.9
361 */
362 public final String trn(String text, String pluralText, long n, Object o1, Object o2)
363 {
364 return trn(text, pluralText, n, new Object[]{ o1, o2 });
365 }
366
367 /**
368 * Overloaded method that invokes
369 * {@link #trn(String, String, long, Object[])} passing <code>Object</code>
370 * arguments as an array.
371 *
372 * @since 0.9
373 */
374 public final String trn(String text, String pluralText, long n, Object o1, Object o2, Object o3)
375 {
376 return trn(text, pluralText, n, new Object[]{ o1, o2, o3 });
377 }
378
379 /**
380 * Overloaded method that invokes
381 * {@link #trn(String, String, long, Object[])} passing <code>Object</code>
382 * arguments as an array.
383 *
384 * @since 0.9
385 */
386 public final String trn(String text, String pluralText, long n, Object o1, Object o2, Object o3, Object o4)
387 {
388 return trn(text, pluralText, n, new Object[]{ o1, o2, o3, o4 });
389 }
390
391 /**
392 * Returns the plural form for <code>n<code> of the translation of ???
393 *
394 * Based on GettextResource.java that is part of GNU gettext for Java
395 * Copyright (C) 2001 Free Software Foundation, Inc.
396 *
397 * @param bundle a ResourceBundle
398 * @param text the key string to be translated, an ASCII string
399 * @param pluralText its English plural form
400 * @return the translation of <code>text</code> depending on <code>n</code>,
401 * or <code>text</code> or <code>pluralText</code> if none is found
402 */
403 private static String trnInternal(ResourceBundle orgBundle, String text, String pluralText, long n)
404 {
405 ResourceBundle bundle = orgBundle;
406 do {
407 boolean isGetTextBundle = false;
408 boolean hasPluralHandling = false;
409 Method handleGetObjectMethod = null;
410 Method getParentMethod = null;
411 Method lookupMethod = null;
412 Method pluralEvalMethod = null;
413 try {
414 handleGetObjectMethod = bundle.getClass().getMethod("handleGetObject", new Class[]{ String.class });
415 getParentMethod = bundle.getClass().getMethod("getParent", new Class[0]);
416 isGetTextBundle = Modifier.isPublic(handleGetObjectMethod.getModifiers());
417 lookupMethod = bundle.getClass().getMethod("lookup", new Class[]{ String.class });
418 pluralEvalMethod = bundle.getClass().getMethod("pluralEval", new Class[]{ Long.TYPE });
419 hasPluralHandling = true;
420 }
421 catch (Exception e) {}
422 if (isGetTextBundle) {
423 // GNU gettext generated bundle
424 if (hasPluralHandling) {
425 // GNU gettext generated bundle w/ plural handling
426 try {
427 Object localValue = lookupMethod.invoke(bundle, new Object[]{ text });
428 if (localValue.getClass().isArray()) {
429 String[] pluralforms = (String[])localValue;
430 long index = 0;
431 try {
432 index = ((Long)pluralEvalMethod.invoke(bundle, new Object[]{ new Long(n) }))
433 .longValue();
434 if (!(index >= 0 && index < pluralforms.length)) {
435 index = 0;
436 }
437 }
438 catch (IllegalAccessException e) {}
439 return pluralforms[(int)index];
440 }
441 else {
442 // Found the value. It doesn't depend on n in this
443 // case.
444 return (String)localValue;
445 }
446 }
447 catch (Exception e) {}
448 }
449 else {
450 // GNU gettext generated bundle w/o plural handling
451 try {
452 Object localValue = handleGetObjectMethod.invoke(bundle, new Object[]{ text });
453 if (localValue != null) {
454 return (String)localValue;
455 }
456 }
457 catch (Exception e) {}
458 }
459 bundle = null;
460 try {
461 bundle = (ResourceBundle)getParentMethod.invoke(bundle, new Object[0]);
462 }
463 catch (Exception e) {}
464 }
465 else {
466 return bundle.getString(text);
467 }
468 }
469 while (bundle != null);
470 throw new MissingResourceException("Can not find resource for key " + text + " in bundle "
471 + orgBundle.getClass().getName(), orgBundle.getClass().getName(), text);
472 }
473
474 /**
475 * Disambiguates translation keys.
476 *
477 * @param context
478 * the context of the text to be translated
479 * @param text
480 * the ambiguous key message in the source locale
481 * @return <code>text</code> if the locale of the underlying resource
482 * bundle equals the source code locale, the translation of
483 * <code>comment</code> otherwise.
484 * @see #setSourceCodeLocale(Locale)
485 * @since 0.9
486 */
487 public final String trc(String context, String text)
488 {
489 if (sourceCodeLocale.equals(getResources().getLocale())) {
490 return text;
491 } else {
492 String key = context + CONTEXT_GLUE + text;
493 String translated = tr(key);
494 // if no translation was found return text in source locale
495 return translated == key ? text : translated;
496 }
497 }
498
499 /**
500 * Returns the plural form for <code>n</code> of the translation of
501 * <code>text</code>.
502 *
503 * @param context
504 * the context of the message to disambiguate it when translating
505 * @param text
506 * the key string to be translated.
507 * @param pluralText
508 * the plural form of <code>text</code>.
509 * @param n
510 * value that determines the plural form
511 * @return the translated text
512 * @since 0.9.5
513 */
514 public final String trnc(String context, String singularText, String pluralText, long n) {
515 try {
516 return trnInternal(bundle, context + CONTEXT_GLUE + singularText, pluralText, n);
517 }
518 catch (MissingResourceException e) {
519 return (n == 1) ? singularText : pluralText;
520 }
521 }
522
523 /**
524 * Returns the plural form for <code>n</code> of the translation of
525 * <code>text</code>.
526 *
527 * @param context
528 * the context of the message to disambiguate it when translating
529 * @param text
530 * the key string to be translated.
531 * @param pluralText
532 * the plural form of <code>text</code>.
533 * @param n
534 * value that determines the plural form
535 * @param objects
536 * object args to be formatted and substituted.
537 * @return the translated text
538 * @since 0.9
539 */
540 public final String trnc(String context, String singularText, String pluralText, long n, Object[] objects) {
541 return MessageFormat.format(trnc(context, singularText, pluralText, n), objects);
542 }
543
544 /**
545 * Overloaded method that invokes
546 * {@link #trnc(String, String, String, long, Object[]) passing <code>obj</code>
547 * arguments as an array.
548 *
549 * @since 0.9.5
550 */
551 public final String trnc(String comment, String singularText, String pluralText, long n, Object obj) {
552 return MessageFormat.format(trnc(comment, singularText, pluralText, n), new Object[] { obj });
553 }
554
555 /**
556 * Overloaded method that invokes
557 * {@link #trnc(String, String, String, long, Object[]) passing <code>obj1</code> and <code>obj2</code>
558 * arguments as an array.
559 *
560 * @since 0.9.5
561 */
562 public final String trnc(String comment, String singularText, String pluralText, long n, Object obj1, Object obj2) {
563 return MessageFormat.format(trnc(comment, singularText, pluralText, n), new Object[] { obj1, obj2 });
564 }
565
566 /**
567 * Overloaded method that invokes
568 * {@link #trnc(String, String, String, long, Object[]) passing <code>obj1</code>, <code>obj2</code> and <code>obj3</code>
569 * arguments as an array.
570 *
571 * @since 0.9.5
572 */
573 public final String trnc(String comment, String singularText, String pluralText, long n, Object obj1, Object obj2, Object obj3) {
574 return MessageFormat.format(trnc(comment, singularText, pluralText, n), new Object[] { obj1, obj2, obj3 });
575 }
576
577 /**
578 * Overloaded method that invokes
579 * {@link #trnc(String, String, String, long, Object[]) passing <code>obj1</code>, <code>obj2</code>, <code>obj3</code> and <code>obj4</code>
580 * arguments as an array.
581 *
582 * @since 0.9.5
583 */
584 public final String trnc(String comment, String singularText, String pluralText, long n, Object obj1, Object obj2, Object obj3, Object obj4) {
585 return MessageFormat.format(trnc(comment, singularText, pluralText, n), new Object[] { obj1, obj2, obj3, obj4 });
586 }
587
588 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Felix Berger
4 * Copyright (C) 2005 Steffen Pingel
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20 package org.xnap.commons.i18n;
21
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Locale;
28 import java.util.Map;
29
30 /**
31 * Stores a list of {@link I18n} objects by a String key.
32 *
33 * @author Steffen Pingel
34 */
35 class I18nCache {
36
37 /**
38 * Map<String, List<I18n>>, list is synchronized too.
39 */
40 private final Map i18nByPackage = Collections.synchronizedMap(new HashMap());
41
42 I18nCache()
43 {
44 }
45
46 public void clear()
47 {
48 i18nByPackage.clear();
49 }
50
51 public I18n get(final String packageName, final Locale locale)
52 {
53 if (locale == null) {
54 throw new NullPointerException("locale is null");
55 }
56
57 List list = (List)i18nByPackage.get(packageName);
58 if (list != null) {
59 synchronized (list) {
60 for (Iterator it = list.iterator(); it.hasNext();) {
61 I18n i18n = (I18n)it.next();
62 if (locale.equals(i18n.getLocale())) {
63 return i18n;
64 }
65 }
66 }
67 }
68 return null;
69 }
70
71 public void put(String packageName, I18n i18n)
72 {
73 List list;
74 synchronized (i18nByPackage) {
75 list = (List)i18nByPackage.get(packageName);
76 if (list == null) {
77 list = Collections.synchronizedList(new ArrayList(2));
78 i18nByPackage.put(packageName, list);
79 }
80 }
81 list.add(i18n);
82 }
83
84 public void visit(final Visitor visitor)
85 {
86 List[] lists;
87 synchronized (i18nByPackage) {
88 lists = (List[])i18nByPackage.values().toArray(new List[0]);
89 }
90 for (int i = 0; i < lists.length; i++) {
91 List list = lists[i];
92 synchronized (list) {
93 for (Iterator it2 = list.iterator(); it2.hasNext();) {
94 I18n i18n = (I18n)it2.next();
95 visitor.visit(i18n);
96 }
97 }
98 }
99 }
100
101 public static interface Visitor {
102
103 void visit(I18n i18n);
104
105 }
106
107 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Felix Berger
4 * Copyright (C) 2005 Steffen Pingel
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20 package org.xnap.commons.i18n;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.Locale;
25 import java.util.MissingResourceException;
26 import java.util.Properties;
27
28 /**
29 * Factory class that creates and caches I18n instances.
30 * <p>
31 * Given a {@link Class} object the factory looks up the resource bundle
32 * responsible for handling message translations. The bundle is returned with an
33 * {@link I18n} object wrapped around it, which provides the translation
34 * methods. The lookup is described at {@link #getI18n(Class,String)}.
35 * <p>
36 * Use the factory for creating <code>I18n</code> objects to make sure no
37 * extraneous objects are created.
38 *
39 * @author Felix Berger
40 * @author Tammo van Lessen
41 * @author Steffen Pingel
42 * @since 0.9
43 */
44 public class I18nFactory {
45
46 private static final String BASENAME_KEY = "basename";
47
48 /**
49 * Use the default configuration.
50 *
51 * @since 0.9.1
52 */
53 public static final int DEFAULT = 0;
54 /**
55 * Fall back to a default resource bundle that returns the passed text if no
56 * resource bundle can be located.
57 *
58 * @since 0.9.1
59 */
60 public static final int FALLBACK = 1 << 0;
61 /**
62 * Look for files named {@link #PROPS_FILENAME} to determine the basename.
63 *
64 * @since 0.9.1
65 */
66 public static final int READ_PROPERTIES = 2 << 0;
67 /**
68 * Do not cache {@link I18n} instance.
69 *
70 * @since 0.9.1
71 */
72 public static final int NO_CACHE = 4 << 0;
73
74 /**
75 * Default name for Message bundles, is "i18n.Messages".
76 *
77 * @since 0.9.1
78 */
79 public static final String DEFAULT_BASE_NAME = "i18n.Messages";
80
81 /**
82 * Filename of the properties file that contains the i18n properties, is
83 * "i18n.properties".
84 *
85 * @since 0.9
86 */
87 public static final String PROPS_FILENAME = "i18n.properties";
88
89 private static final I18nCache i18nCache = new I18nCache();
90
91 private I18nFactory()
92 {
93 }
94
95 /**
96 * Clears the cache of i18n objects. Used by the test classes.
97 */
98 static void clearCache()
99 {
100 i18nCache.visit(new I18nCache.Visitor() {
101
102 public void visit(I18n i18n)
103 {
104 I18nManager.getInstance().remove(i18n);
105 }
106 });
107 i18nCache.clear();
108 }
109
110 /**
111 * Calls {@link #getI18n(Class, Locale) getI18n(clazz, Locale.getDefault())}.
112 */
113 public static I18n getI18n(final Class clazz)
114 {
115 return getI18n(clazz, Locale.getDefault());
116 }
117
118 /**
119 * Calls {@link #getI18n(Class, Locale, int) getI18n(clazz, locale,
120 * READ_PROPERTIES)}.
121 *
122 * @since 0.9.1
123 */
124 public static I18n getI18n(final Class clazz, final Locale locale)
125 {
126 return getI18n(clazz, locale, READ_PROPERTIES);
127 }
128
129 /**
130 * Returns the I18n instance responsible for translating messages in the
131 * package specified by <code>clazz</code>.
132 * <p>
133 * Lookup works by iterating upwards in the package hierarchy: First the
134 * internal cache is asked for an I18n object for a package, otherwise the
135 * algorithm looks for an <code>i18n.properties</code> file in the
136 * package. The properties file is queried for a key named
137 * <code>basename</code> whose value should be the fully qualified
138 * resource/class name of the resource bundle, e.g
139 * <code>org.xnap.commons.i18n.Messages</code>.
140 * <p>
141 * If after the first iteration no I18n instance has been found, a second
142 * search begins by looking for resource bundles having the name
143 * <code>baseName</code>.
144 *
145 * @param clazz
146 * the package hierarchy of the clazz and its class loader are
147 * used for resolving and loading the resource bundle
148 * @param baseName
149 * the name of the underlying resource bundle
150 * @param locale
151 * the locale of the underlying resource bundle
152 * @param flags
153 * a combination of these configuration flags: {@link #FALLBACK}
154 * @return created or cached <code>I18n</code> instance
155 * @throws MissingResourceException
156 * if no resource bundle was found
157 * @since 0.9.1
158 */
159 public static I18n getI18n(final Class clazz, final Locale locale, final int flags)
160 {
161 ClassLoader classLoader = getClassLoader(clazz.getClassLoader());
162
163 String bundleName = null;
164 if (isReadPropertiesSet(flags)) {
165 String path = clazz.getName();
166 int index;
167 do {
168 index = path.lastIndexOf('.');
169 path = (index != -1) ? path.substring(0, index) : "";
170 bundleName = readFromPropertiesFile(path, locale, classLoader);
171 }
172 while (bundleName == null && index != -1);
173 }
174
175 if (bundleName == null) {
176 bundleName = DEFAULT_BASE_NAME;
177 }
178
179 return getI18n("", bundleName, classLoader, locale, flags);
180 }
181
182 /**
183 * Calls
184 * {@link #getI18n(Class, String, Locale) getI18n(clazz, bundleName, Locale.getDefault())}.
185 *
186 * @since 0.9
187 */
188 public static I18n getI18n(final Class clazz, final String bundleName)
189 {
190 return getI18n(clazz, bundleName, Locale.getDefault());
191 }
192
193 /**
194 * Calls
195 * {@link #getI18n(Class, String, Locale, int) getI18n(clazz, bundleName, locale, DEFAULT)}.
196 *
197 * @since 0.9.1
198 */
199 public static I18n getI18n(final Class clazz, final String bundleName, final Locale locale)
200 {
201 return getI18n(clazz, bundleName, locale, DEFAULT);
202 }
203
204 /**
205 * Calls
206 * {@link #getI18n(Class, String, Locale) getI18n(getPackageName(clazz), bundleName, clazz.getClassLoader(), locale, DEFAULT)}.
207 *
208 * @since 0.9.1
209 */
210 public static I18n getI18n(final Class clazz, final String bundleName, final Locale locale, int flags)
211 {
212 return getI18n(clazz.getName(), bundleName, clazz.getClassLoader(), locale, flags);
213 }
214
215 /**
216 * @since 0.9.1
217 */
218 public static I18n getI18n(final String path, final String bundleName, final ClassLoader classLoader, final Locale locale,
219 final int flags)
220 {
221 int index;
222 String prefix = path;
223 do {
224 // chop of last segment of path
225 index = prefix.lastIndexOf('.');
226 prefix = (index != -1) ? prefix.substring(0, index) : "";
227 String name = prefix.length() == 0 ? bundleName : prefix + "." + bundleName;
228
229 // check cache
230 I18n i18n = i18nCache.get(name, locale);
231 if (i18n != null) {
232 return i18n;
233 }
234
235 // look for resource bundle in class path
236 i18n = findByBaseName(name, locale, getClassLoader(classLoader), flags);
237 if (i18n != null) {
238 if ((flags & NO_CACHE) == 0) {
239 i18nCache.put(name, i18n);
240 }
241 return i18n;
242 }
243 }
244 while (index != -1);
245
246 // fallback to default bundle
247 if (isFallbackSet(flags)) {
248 I18n i18n = i18nCache.get("", locale);
249 if (i18n == null) {
250 i18n = new I18n(new EmptyResourceBundle(locale));
251 i18nCache.put("", i18n);
252 }
253 return i18n;
254 }
255
256 throw new MissingResourceException("Resource bundle not found", path, bundleName);
257 }
258
259 static ClassLoader getClassLoader(ClassLoader classLoader) {
260 return (classLoader != null) ? classLoader : ClassLoader.getSystemClassLoader();
261 }
262
263 /**
264 * Tries to create an I18n instance from a properties file.
265 *
266 * @param path
267 * @param loader
268 * @return null if no properties file was found
269 * @throws MissingResourceException
270 * if properties file was found but specified resource not
271 */
272 static String readFromPropertiesFile(final String path, final Locale locale, final ClassLoader loader)
273 {
274 Properties props = new Properties();
275 String filename = path.length() == 0 ? PROPS_FILENAME : path.replace('.', '/') + "/" + PROPS_FILENAME;
276 InputStream in = loader.getResourceAsStream(filename);
277 if (in != null) {
278 try {
279 props.load(in);
280 }
281 catch (IOException e) {
282 // XXX now what?
283 }
284 finally {
285 try {
286 in.close();
287 }
288 catch (IOException e) {
289 // this exception is lost
290 }
291 }
292 return props.getProperty(BASENAME_KEY);
293 }
294 return null;
295 }
296
297 /**
298 * Uses the class loader to look for a messages properties file.
299 *
300 * @param baseName
301 * the base name of the resource bundle
302 * @param path
303 * the path that prefixes baseName
304 * @param loader
305 * the class loader used to look up the bundle
306 * @param flags
307 * @return the created instance
308 */
309 static I18n findByBaseName(final String baseName, final Locale locale, final ClassLoader loader, int flags)
310 {
311 try {
312 return createI18n(baseName, locale, loader, flags);
313 }
314 catch (MissingResourceException e) {
315 return null;
316 }
317 }
318
319 /**
320 * Creates a new i18n instance and registers it with {@link I18nManager}.
321 *
322 * @param baseName
323 * the base name of the resource bundle
324 * @param locale
325 * the locale
326 * @param loader
327 * the class loader used to look up the bundle
328 * @return the created instance
329 */
330 private static I18n createI18n(final String baseName, final Locale locale, final ClassLoader loader, final int flags)
331 {
332 I18n i18n = new I18n(baseName, locale, loader);
333 if (!isNoCacheSet(flags)) {
334 I18nManager.getInstance().add(i18n);
335 }
336 return i18n;
337 }
338
339 private static boolean isFallbackSet(final int flags)
340 {
341 return (flags & FALLBACK) != 0;
342 }
343
344 private static boolean isReadPropertiesSet(final int flags)
345 {
346 return (flags & READ_PROPERTIES) != 0;
347 }
348
349 private static boolean isNoCacheSet(final int flags)
350 {
351 return (flags & NO_CACHE) != 0;
352 }
353
354 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Felix Berger
4 * Copyright (C) 2005 Steffen Pingel
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20 package org.xnap.commons.i18n;
21
22 import java.lang.ref.WeakReference;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Locale;
28
29 /**
30 * Manager class that maintains a set of {@link org.xnap.commons.i18n.I18n}
31 * objects and {@link org.xnap.commons.i18n.LocaleChangeListener} objects.
32 * <p>
33 * The locale of all managed <code>I18n</code> objects can be changed by
34 * invoking {@link org.xnap.commons.i18n.I18nManager#setDefaultLocale(Locale)}.
35 *
36 * @author Felix Berger
37 * @author Steffen Pingel
38 * @since 0.9
39 */
40 public class I18nManager {
41
42 private static I18nManager instance = new I18nManager();
43
44 /** List of managed {@link I18n} objects. */
45 List i18ns = Collections.synchronizedList(new ArrayList());
46
47 /** List of managed {@link LocaleChangeListener} objects. */
48 List localeChangeListeners = new ArrayList();
49
50 private I18nManager()
51 {
52 }
53
54 /**
55 * Returns the global <code>I18Manger</code> singleton.
56 *
57 * @return the <code>I18Manger</code> instance
58 * @since 0.9
59 */
60 public static I18nManager getInstance()
61 {
62 return instance;
63 }
64
65 /**
66 * Adds <code>i18n</code> to the list of managed <code>I18n</code>
67 * objects.
68 *
69 * @param i18n
70 * the <code>I18n</code> instance
71 * @see #setDefaultLocale(Locale)
72 * @see #remove(I18n)
73 * @since 0.9
74 */
75 public void add(I18n i18n)
76 {
77 i18ns.add(i18n);
78 }
79
80 /**
81 * Sets the locale for all I18n instances that were instantiated through the
82 * factory.
83 * <p>
84 * Use this method to globally change the locale for all I18n based
85 * translations.
86 * <p>
87 * NOTE: This only works if the objects that display messages do not cache
88 * translated messages.
89 * <p>
90 *
91 * @param locale
92 * the new default locale
93 * @see I18n#setLocale(Locale)
94 * @since 0.9
95 */
96 public void setDefaultLocale(Locale locale)
97 {
98 synchronized (i18ns) {
99 for (Iterator it = i18ns.iterator(); it.hasNext();) {
100 I18n i18n = (I18n)it.next();
101 i18n.setLocale(locale);
102 }
103 }
104 fireLocaleChangedEvent(locale);
105 }
106
107 /**
108 * Adds a listener that is notified when the default locale has been
109 * changed.
110 *
111 * @param listener
112 * the listener
113 * @see #setDefaultLocale(Locale)
114 * @since 0.9
115 */
116 public void addLocaleChangeListener(LocaleChangeListener listener)
117 {
118 synchronized (localeChangeListeners) {
119 localeChangeListeners.add(listener);
120 }
121 }
122
123 /**
124 * Adds a listener that is notified when the default locale has been changed
125 * using a {@link WeakReference}. The listener is removed when it has been
126 * cleaned up by the garbage collection.
127 * <p>
128 * This is useful for temporary objects that may have an indeterminate
129 * lifetime such as dialogs.
130 *
131 * @param listener
132 * the listener
133 * @see #setDefaultLocale(Locale)
134 * @since 0.9
135 */
136 public void addWeakLocaleChangeListener(LocaleChangeListener listener)
137 {
138 synchronized (localeChangeListeners) {
139 localeChangeListeners.add(new WeakLocaleChangeListener(listener));
140 }
141 }
142
143 /**
144 * Removes <code>i18n</code> from the list of managed <code>I18n</code>
145 * objects.
146 *
147 * @param i18n
148 * the <code>I18n</code> instance
149 * @see #add(I18n)
150 * @since 0.9
151 */
152 public void remove(I18n i18n)
153 {
154 i18ns.remove(i18n);
155 }
156
157 /**
158 * Removes <code>listener</code> from the list of objects that are
159 * notified when the locale has changed.
160 *
161 * @param listener
162 * the listener
163 * @since 0.9
164 */
165 public void removeLocaleChangeListener(LocaleChangeListener listener)
166 {
167 synchronized (localeChangeListeners) {
168 localeChangeListeners.remove(listener);
169 }
170 }
171
172 /**
173 * Notifies listeners of a locale change.
174 *
175 * @param newLocale
176 * new locale
177 * @since 0.9
178 */
179 protected void fireLocaleChangedEvent(Locale newLocale)
180 {
181 LocaleChangeListener[] listeners;
182 synchronized (localeChangeListeners) {
183 listeners = (LocaleChangeListener[])localeChangeListeners.toArray(new LocaleChangeListener[0]);
184 }
185 if (listeners.length > 0) {
186 LocaleChangeEvent event = new LocaleChangeEvent(I18nFactory.class, newLocale);
187 for (int i = listeners.length - 1; i >= 0; i--) {
188 listeners[i].localeChanged(event);
189 }
190 }
191 }
192
193 private static class WeakLocaleChangeListener implements LocaleChangeListener {
194
195 private WeakReference reference;
196
197 public WeakLocaleChangeListener(LocaleChangeListener listener)
198 {
199 reference = new WeakReference(listener);
200 }
201
202 public void localeChanged(LocaleChangeEvent event)
203 {
204 Object listener = reference.get();
205 if (listener != null) {
206 ((LocaleChangeListener)listener).localeChanged(event);
207 }
208 else {
209 I18nManager.getInstance().removeLocaleChangeListener(this);
210 }
211 }
212
213 }
214
215 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import java.util.EventObject;
22 import java.util.Locale;
23
24 /**
25 * Provides information about a locale change.
26 *
27 * @author Steffen Pingel
28 * @since 0.9
29 */
30 public class LocaleChangeEvent extends EventObject {
31
32 private static final long serialVersionUID = 7640942181212009222L;
33
34 private Locale newLocale;
35
36 /**
37 * Constructs the event.
38 * @param source the source of the event
39 * @param newLocale the new locale
40 * @since 0.9
41 */
42 public LocaleChangeEvent(Object source, Locale newLocale)
43 {
44 super(source);
45
46 this.newLocale = newLocale;
47 }
48
49 /**
50 * Returns the new locale.
51 *
52 * @return the new locale
53 * @since 0.9
54 */
55 public Locale getNewLocale()
56 {
57 return newLocale;
58 }
59
60 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import java.util.Locale;
22
23 /**
24 * Defines the requirements for classes that get notified when the locale
25 * is changed.
26 *
27 * <p>A component that implements this interface may dynamically change the
28 * language of all user visible strings.
29 *
30 * @see org.xnap.commons.i18n.I18nManager#setDefaultLocale(Locale)
31 * @author Steffen Pingel
32 * @since 0.9
33 */
34 public interface LocaleChangeListener {
35
36 /**
37 * Invoked when the local has changed.
38 *
39 * @param event provides information about the new locale
40 * @since 0.9
41 */
42 void localeChanged(LocaleChangeEvent event);
43
44 }
0 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
1 <html>
2 <head>
3 </head>
4 <body>
5 <p>Provides classes for internationalization (i18n).</p>
6
7 <p>To learn how to make use of the Gettext Commons internationalization,
8 please have a look at this <a href="
9 http://xnap-commons.sourceforge.net/gettext-commons/tutorial.html">tutorial</a>.</p>
10
11 </body>
12 </html>
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import junit.framework.TestCase;
22
23 /**
24 * @author Steffen Pingel
25 */
26 public class EmptyResourceBundleTest extends TestCase {
27
28 public void test()
29 {
30 EmptyResourceBundle bundle = new EmptyResourceBundle(null);
31 assertEquals("Foo", bundle.getObject("Foo"));
32 assertFalse(bundle.getKeys().hasMoreElements());
33 }
34
35 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import java.util.Locale;
22
23 import junit.framework.TestCase;
24
25 import org.xnap.commons.i18n.testpackage.MockResourceBundle;
26
27 /**
28 * @author Steffen Pingel
29 */
30 public class I18nCacheTest extends TestCase {
31
32 public void testGet()
33 {
34 I18nCache cache = new I18nCache();
35 I18n i18n = new I18n(new MockResourceBundle());
36 cache.put("foo", i18n);
37 assertNull(cache.get("foo", Locale.getDefault()));
38 try {
39 cache.get("foo", null);
40 fail("Expected IllegalArgumentException");
41 }
42 catch (IllegalArgumentException expected) {}
43 i18n.setLocale(Locale.ENGLISH);
44 assertSame(i18n, cache.get("foo", Locale.ENGLISH));
45 }
46
47 public void testClear()
48 {
49 I18nCache cache = new I18nCache();
50 I18n i18n = new I18n(new MockResourceBundle());
51 i18n.setLocale(Locale.ENGLISH);
52 cache.put("foo", i18n);
53 assertNotNull(cache.get("foo", Locale.ENGLISH));
54 cache.clear();
55 assertNull(cache.get("foo", Locale.ENGLISH));
56 }
57
58 public void testVisit()
59 {
60 I18nCache cache = new I18nCache();
61 final I18n i18n = new I18n(new MockResourceBundle());
62 cache.put("foo", i18n);
63 final int[] count = new int[1];
64 cache.visit(new I18nCache.Visitor() {
65
66 public void visit(I18n visited)
67 {
68 assertSame(i18n, visited);
69 count[0]++;
70 }
71 });
72 assertEquals(1, count[0]);
73 }
74
75 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import java.util.Locale;
22
23 import junit.framework.TestCase;
24
25 import org.xnap.commons.i18n.testpackage.MockResourceBundle;
26 import org.xnap.commons.i18n.testpackage.noresources.HasNoOwnResources;
27 import org.xnap.commons.i18n.testpackage.resources.HasItsOwnResources;
28
29 /**
30 * @author Felix Berger
31 */
32 public class I18nFactoryTest extends TestCase {
33
34 private static Locale[] LOCALES = { Locale.GERMAN, Locale.FRENCH };
35
36 private static String[] VALUES = { "Wert", "valeur" };
37
38 private Locale savedDefault;
39
40 private String packageName;
41
42 protected void setUp() throws Exception
43 {
44 packageName = MockResourceBundle.class.getName();
45 packageName = packageName.substring(0, packageName.lastIndexOf('.'));
46
47 savedDefault = Locale.getDefault();
48 Locale.setDefault(Locale.GERMAN);
49
50 I18nFactory.clearCache();
51 }
52
53 protected void tearDown() throws Exception
54 {
55 Locale.setDefault(savedDefault);
56 }
57
58 public void testFindByBaseName()
59 {
60 for (int i = 0; i < LOCALES.length; i++) {
61 Locale.setDefault(LOCALES[i]);
62 I18n i18n = I18nFactory.findByBaseName(packageName + ".TestMessages", Locale.getDefault(),
63 MockResourceBundle.class.getClassLoader(), I18nFactory.DEFAULT);
64 assertEquals(LOCALES[i], i18n.getResources().getLocale());
65 assertEquals(VALUES[i], i18n.getResources().getString("value"));
66 assertEquals(VALUES[i], i18n.tr("value"));
67 }
68
69 // same for mock up
70 I18n i18n = I18nFactory.findByBaseName(packageName + ".MockResourceBundle", Locale.getDefault(), getClass()
71 .getClassLoader(), I18nFactory.DEFAULT);
72 assertEquals(MockResourceBundle.class, i18n.getResources().getClass());
73 assertEquals("value", i18n.getResources().getString("value"));
74 assertEquals("value", i18n.tr("value"));
75 }
76
77 public void testReadFromPropertiesFile()
78 {
79 String baseName = I18nFactory.readFromPropertiesFile(packageName, Locale.getDefault(), getClass()
80 .getClassLoader());
81 assertEquals("org.xnap.commons.i18n.testpackage.TestMessages", baseName);
82 }
83
84 public void testGetI18n()
85 {
86 I18n i18n = I18nFactory.getI18n(MockResourceBundle.class);
87 assertNotSame(MockResourceBundle.class, i18n.getResources().getClass());
88 i18n = I18nFactory.getI18n(MockResourceBundle.class, "MockResourceBundle");
89 assertSame(MockResourceBundle.class, i18n.getResources().getClass());
90 }
91
92 public void testGetI18nFromDefaultPackage()
93 {
94 I18n i18n = I18nFactory.getI18n(MockResourceBundle.class, "DefaultMessages", Locale.ENGLISH);
95 assertEquals("DefaultBundle", i18n.tr("source"));
96 }
97
98 public void testOwnResources()
99 {
100 I18n i18n = I18nFactory.getI18n(HasItsOwnResources.class);
101 i18n.setLocale(Locale.GERMAN);
102 assertEquals("yes", i18n.tr("own"));
103 }
104
105 public void testNoOwnResources()
106 {
107 I18n i18n = I18nFactory.getI18n(HasNoOwnResources.class);
108 i18n.setLocale(Locale.GERMAN);
109 assertEquals(Locale.GERMAN, i18n.getResources().getLocale());
110 assertEquals("Wert", i18n.tr("value"));
111 i18n.setLocale(Locale.FRENCH);
112 assertEquals(Locale.FRENCH, i18n.getResources().getLocale());
113 assertEquals("valeur", i18n.tr("value"));
114 }
115
116 public void testGetI18nFallback()
117 {
118 I18n i18n = I18nFactory.getI18n(HasNoOwnResources.class, "NonExistant", Locale.getDefault(),
119 I18nFactory.FALLBACK);
120 assertTrue(i18n.getResources() instanceof EmptyResourceBundle);
121 }
122
123 public void testSetResources()
124 {
125 try {
126 I18n i18n = I18nFactory.getI18n(MockResourceBundle.class);
127 i18n.setResources(null);
128 fail("NullPointerException expected");
129 }
130 catch (NullPointerException npe) {}
131 I18n i18n = I18nFactory.getI18n(MockResourceBundle.class);
132 String baseName = MockResourceBundle.class.getName();
133 i18n.setResources(baseName, Locale.GERMAN, MockResourceBundle.class.getClassLoader());
134 assertEquals(MockResourceBundle.class, i18n.getResources().getClass());
135 }
136
137 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import java.util.Locale;
22 import junit.framework.TestCase;
23 import org.xnap.commons.i18n.testpackage.MockResourceBundle;
24
25 /**
26 * @author Felix Berger
27 */
28 public class I18nManagerTest extends TestCase
29 {
30 private Locale savedDefault;
31
32 protected void setUp() throws Exception
33 {
34 I18nFactory.clearCache();
35
36 savedDefault = Locale.getDefault();
37 Locale.setDefault(Locale.GERMAN);
38 }
39
40 protected void tearDown() throws Exception
41 {
42 Locale.setDefault(savedDefault);
43 }
44
45 public void testSetLocale()
46 {
47 I18n i18n = I18nFactory.getI18n(MockResourceBundle.class);
48 assertEquals(Locale.GERMAN, i18n.getResources().getLocale());
49 I18nManager.getInstance().setDefaultLocale(Locale.FRENCH);
50 assertEquals(Locale.FRENCH, i18n.getResources().getLocale());
51 I18nManager.getInstance().setDefaultLocale(Locale.GERMAN);
52 assertEquals(Locale.GERMAN, i18n.getResources().getLocale());
53 }
54
55 public void testListener()
56 {
57 MyLocaleChangeListener listener = new MyLocaleChangeListener();
58 I18nManager.getInstance().addLocaleChangeListener(listener );
59 assertEquals(0, listener.count);
60 I18nManager.getInstance().setDefaultLocale(Locale.GERMAN);
61 assertEquals(1, listener.count);
62 assertEquals(Locale.GERMAN, listener.newLocale);
63 I18nManager.getInstance().removeLocaleChangeListener(listener);
64 I18nManager.getInstance().setDefaultLocale(Locale.FRENCH);
65 assertEquals(1, listener.count);
66 assertEquals(Locale.GERMAN, listener.newLocale);
67 }
68
69 public void testWeakListener()
70 {
71 int listenerCount = I18nManager.getInstance().localeChangeListeners.size();
72 MyLocaleChangeListener listener = new MyLocaleChangeListener();
73 I18nManager.getInstance().addWeakLocaleChangeListener(listener );
74 assertEquals(0, listener.count);
75 assertEquals(listenerCount + 1, I18nManager.getInstance().localeChangeListeners.size());
76 I18nManager.getInstance().setDefaultLocale(Locale.GERMAN);
77 assertEquals(1, listener.count);
78 listener = null;
79 System.gc();
80 I18nManager.getInstance().setDefaultLocale(Locale.FRENCH);
81 assertEquals(listenerCount, I18nManager.getInstance().localeChangeListeners.size());
82 }
83
84 private class MyLocaleChangeListener implements LocaleChangeListener {
85 int count;
86 Locale newLocale;
87 public void localeChanged(LocaleChangeEvent event)
88 {
89 count++;
90 newLocale = event.getNewLocale();
91 }
92 };
93
94 }
0 /*
1 * Gettext Commons
2 *
3 * Copyright (C) 2005 Steffen Pingel
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19 package org.xnap.commons.i18n;
20
21 import java.util.Locale;
22 import java.util.MissingResourceException;
23
24 import junit.framework.TestCase;
25
26 import org.xnap.commons.i18n.testpackage.MockResourceBundle;
27
28 /**
29 * @author Steffen Pingel
30 * @author Felix Berger
31 */
32 public class I18nTest extends TestCase {
33
34 public static final String BASENAME = "org.xnap.commons.i18n.Messages";
35
36 private I18n i18nDE;
37
38 private I18n i18nEN;
39
40 protected void setUp() throws Exception
41 {
42 try {
43 i18nDE = new I18n(BASENAME, Locale.GERMAN, getClass().getClassLoader());
44 }
45 catch (MissingResourceException e) {
46 throw new RuntimeException(
47 "Please make sure you run 'mvn org.xnap.commons:maven-gettext-plugin:dist' before executing tests");
48 }
49 i18nEN = new I18n(BASENAME, Locale.ENGLISH, getClass().getClassLoader());
50 }
51
52 protected void tearDown() throws Exception
53 {
54 }
55
56 public void testTr()
57 {
58 assertEquals("Haus", i18nDE.tr("house"));
59 assertEquals("Maus", i18nDE.tr("mouse"));
60 assertEquals("Automatisch", i18nDE.tr("Automatic"));
61 assertEquals("Erg\u00e4nzung", i18nDE.tr("Completion"));
62 }
63
64 public void testTr1()
65 {
66 assertEquals("House Nr. 2 ", i18nEN.tr("House Nr. {0} ", Integer.valueOf(2)));
67 assertEquals("0", i18nEN.tr("{0}", "0"));
68 }
69
70 public void testTr2()
71 {
72 assertEquals("Foo bar foo", i18nEN.tr("Foo {1} {0}", "foo", "bar"));
73 assertEquals("Foo foo bar", i18nEN.tr("Foo {0} {1}", "foo", "bar"));
74 }
75
76 public void testTr3()
77 {
78 assertEquals("Foo bar baz foo", i18nEN.tr("Foo {1} {2} {0}", "foo", "bar", "baz"));
79 assertEquals("Foo foo bar baz", i18nEN.tr("Foo {0} {1} {2}", "foo", "bar", "baz"));
80 }
81
82 public void testTr4()
83 {
84 assertEquals("Foo bar baz boing foo", i18nEN.tr("Foo {1} {2} {3} {0}", "foo", "bar", "baz", "boing"));
85 assertEquals("Foo foo bar baz boing", i18nEN.tr("Foo {0} {1} {2} {3}", "foo", "bar", "baz", "boing"));
86 }
87
88 public void testMarktr()
89 {
90 assertEquals(I18n.marktr("Foo"), "Foo");
91 }
92
93 public void testTrc()
94 {
95 assertEquals("chat", i18nEN.trc("noun", "chat"));
96 assertEquals("chat", i18nEN.trc("verb", "chat"));
97 assertEquals("Chat", i18nDE.trc("noun", "chat"));
98 assertEquals("Chatten", i18nDE.trc("verb", "chat"));
99 }
100
101 public void testSetLocale()
102 {
103 I18n i18n = new I18n(new MockResourceBundle());
104 assertFalse(i18n.setLocale(Locale.FRENCH));
105 i18n.setResources(MockResourceBundle.class.getName(), Locale.GERMAN, MockResourceBundle.class.getClassLoader());
106 assertTrue(i18n.setLocale(Locale.FRENCH));
107 }
108
109 public void testSetResources()
110 {
111 try {
112 new I18n(null);
113 fail("NullPointerException expected");
114 }
115 catch (NullPointerException npe) {}
116 String baseName = MockResourceBundle.class.getName();
117 try {
118 i18nDE.setResources(null, Locale.GERMAN, MockResourceBundle.class.getClassLoader());
119 fail("NullPointerException expected");
120 }
121 catch (NullPointerException npe) {}
122 try {
123 i18nDE.setResources(baseName, null, MockResourceBundle.class.getClassLoader());
124 fail("NullPointerException expected");
125 }
126 catch (NullPointerException npe) {}
127 try {
128 i18nDE.setResources(baseName, Locale.GERMAN, null);
129 fail("NullPointerException expected");
130 }
131 catch (NullPointerException npe) {}
132 }
133
134 public void testSetSourceCodeLocale()
135 {
136 i18nDE.setSourceCodeLocale(Locale.GERMAN);
137 assertEquals("chat", i18nDE.trc("verb", "chat"));
138 i18nDE.setSourceCodeLocale(Locale.ENGLISH);
139 assertEquals("Chatten", i18nDE.trc("verb", "chat"));
140
141 try {
142 i18nDE.setSourceCodeLocale(null);
143 fail("null pointer exception expected");
144 }
145 catch (NullPointerException npe) {}
146 }
147
148 public void testTrnEN()
149 {
150 assertEquals("Foo", i18nEN.trn("Foo", "{0} Bars", 1));
151 assertEquals("{0} Bars", i18nEN.trn("Foo", "{0} Bars", 2));
152 assertEquals("2 Bars", i18nEN.trn("Foo", "{0} Bars", 2, new Integer(2)));
153 }
154
155 public void testTrnDE()
156 {
157 assertEquals("Datei", i18nDE.trn("File", "{0} Files", 1, new Integer(1)));
158 assertEquals("2 Dateien", i18nDE.trn("File", "{0} Files", 2, new Integer(2)));
159 }
160
161 public void testTrn1()
162 {
163 assertEquals("Foo foo ", i18nEN.trn("Foo {0} ", "Foos {0}", 1, "foo"));
164 }
165
166 public void testTrn2()
167 {
168 assertEquals("Foo bar foo", i18nEN.trn("Foo {1} {0}", "Foos", 1, "foo", "bar"));
169 assertEquals("Foo foo bar", i18nEN.trn("Foo {0} {1}", "Foos", 1, "foo", "bar"));
170 }
171
172 public void testTrn3()
173 {
174 assertEquals("Foo bar baz foo", i18nEN.trn("Foo {1} {2} {0}", "Foos", 1, "foo", "bar", "baz"));
175 assertEquals("Foo foo bar baz", i18nEN.trn("Foo {0} {1} {2}", "Foos", 1, "foo", "bar", "baz"));
176 }
177
178 public void testTrn4()
179 {
180 assertEquals("Foo bar baz boing foo", i18nEN
181 .trn("Foo {1} {2} {3} {0}", "Foos", 1, "foo", "bar", "baz", "boing"));
182 assertEquals("Foo foo bar baz boing", i18nEN
183 .trn("Foo {0} {1} {2} {3}", "Foos", 1, "foo", "bar", "baz", "boing"));
184 }
185
186 public void testSetEmptyResources()
187 {
188 // this should load the empty resource bundle
189 // we have to set the default to italian too, so
190 // ResourceBundle.getBundle(...) doesn't fall back on the default locale
191 // which might be there
192 Locale.setDefault(Locale.ITALIAN);
193 assertTrue(i18nDE.setLocale(Locale.ITALIAN));
194 assertEquals("value", i18nDE.tr("value"));
195 }
196
197 public void testTrcReturnsTextWhenTranslationNotFound() {
198 assertEquals("baobab", i18nDE.trc("dont translate to German", "baobab"));
199 }
200 }
0 package org.xnap.commons.i18n.testpackage;
1
2 import java.util.Enumeration;
3 import java.util.Locale;
4 import java.util.ResourceBundle;
5
6 public class MockResourceBundle extends ResourceBundle
7 {
8
9 private Locale locale;
10
11 public MockResourceBundle()
12 {
13 }
14
15 public Locale getLocale()
16 {
17 return locale;
18 }
19
20 public void setLocale(Locale locale)
21 {
22 this.locale = locale;
23 }
24
25 protected Object handleGetObject(String key)
26 {
27 return "value";
28 }
29
30 public Enumeration getKeys()
31 {
32 return new Enumeration() {
33 boolean gotten = false;
34
35 public boolean hasMoreElements()
36 {
37 return !gotten;
38 }
39
40 public Object nextElement()
41 {
42 gotten = true;
43 return "value";
44 }
45 };
46 }
47
48 }
0 package org.xnap.commons.i18n.testpackage.noresources;
1
2 public class HasNoOwnResources
3 {
4
5 }
0 package org.xnap.commons.i18n.testpackage.resources;
1
2 public class HasItsOwnResources
3 {
4
5 }
0 basename=org.xnap.commons.i18n.Messages
0 basename=org.xnap.commons.i18n.testpackage.TestMessages
0 basename=org.xnap.commons.i18n.testpackage.resources.OwnMessages